Sunday, November 22, 2020

DateTime picker in flutter

...............................................................................................................................................................................................................................
Example : #1 [ Datepicker and time picker ]

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  DateTime _dateTime;
  TimeOfDay _timeOfDay;


  Future<void> gettime() async {
    TimeOfDay timeOfDay = await showTimePicker(
        context: context,
        initialTime: TimeOfDay(
            hour: TimeOfDay.now().hour, minute: TimeOfDay.now().minute));
    setState(() {
      _timeOfDay = timeOfDay;
    });
  }


  Future<void> getdate() async {
    DateTime datetime = await showDatePicker(
        context: context,
        initialDate: DateTime(DateTime.now().year),
        firstDate: DateTime(DateTime.now().year - 20),
        lastDate: DateTime(DateTime.now().year + 2));
    setState(() {
      _dateTime = datetime;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Alert'),
        ),
        body: Center(
          child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
            _dateTime == null
                ? Text('Choose Date')
                : Text(
                    '${_dateTime.year}, ${_dateTime.month}, ${_dateTime.day}'),

            _timeOfDay == null
                ? Text('Choose time')
                : Text('${_timeOfDay.hour},${_timeOfDay.minute}'),

            RaisedButton(
                child: Text('Date Picker'),
                onPressed: () {
                  getdate();
                }),
            RaisedButton(
                child: Text('Show time Picker'),
                onPressed: () {
                  gettime();
                })
          ]),
        ));
  }
}


No comments:

Post a Comment