What is the correct way to add date picker in flutter app? What is the correct way to add date picker in flutter app? ios ios

What is the correct way to add date picker in flutter app?


A simple app showcasing its use:

import 'dart:async';import 'package:flutter/material.dart';void main() => runApp(MyApp());class MyApp extends StatelessWidget {  @override  Widget build(BuildContext context) {    return MaterialApp(      title: 'Flutter Demo',      home: MyHomePage(title: 'Flutter Demo Home Page'),    );  }}class MyHomePage extends StatefulWidget {  MyHomePage({Key key, this.title}) : super(key: key);  final String title;  @override  _MyHomePageState createState() => _MyHomePageState();}class _MyHomePageState extends State<MyHomePage> {  DateTime selectedDate = DateTime.now();  Future<void> _selectDate(BuildContext context) async {    final DateTime picked = await showDatePicker(        context: context,        initialDate: selectedDate,        firstDate: DateTime(2015, 8),        lastDate: DateTime(2101));    if (picked != null && picked != selectedDate)      setState(() {        selectedDate = picked;      });  }  @override  Widget build(BuildContext context) {    return Scaffold(      appBar: AppBar(        title: Text(widget.title),      ),      body: Center(        child: Column(          mainAxisSize: MainAxisSize.min,          children: <Widget>[            Text("${selectedDate.toLocal()}".split(' ')[0]),            SizedBox(height: 20.0,),            RaisedButton(              onPressed: () => _selectDate(context),              child: Text('Select date'),            ),          ],        ),      ),    );  }}

And a Dartpad with it:

https://dartpad.dev/e5a99a851ae747e517b75ac221b73529


Flutter provides showDatePicker function to achieve this. It is part of flutter material library.

You can find complete documentation at showDatePicker.

You can also find implemented example here: Date and Time Picker


for time picker-

Declare this variable at class level

TimeOfDay selectedTime =TimeOfDay.now();

and call this method:-

Future<Null> _selectTime(BuildContext context) async {    final TimeOfDay picked_s = await showTimePicker(        context: context,        initialTime: selectedTime, builder: (BuildContext context, Widget child) {           return MediaQuery(             data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: false),            child: child,          );});    if (picked_s != null && picked_s != selectedTime )      setState(() {        selectedTime = picked_s;      });  }