How To Set Up Date picker In Flutter Using Android

admin_img Posted By Bajarangi soft , Posted On 23-09-2020

All we have to do is pass the minimum and maximum year inside firstDate and lastDate properties and the Date picker will show us all the years between them. We have to use Future keyword with date picker, This method will get us the current selected date on Alert dialog closure event and returns us the date.

Learn How To Add Date picker In Flutter Android App

Step 1
We cannot directly remove the time stamp from showDatePicker() but using the intl.dart package we can easily filter the date stamp from time stamp. So open your flutter project’s pubspec.yaml in code .

dependencies:
  flutter:
    sdk: flutter
  http: ^0.12.0
  intl: ^0.16.0
  smooth_star_rating: 1.0.3

Step 2
After done saving the pubspec.yaml file, Open your flutter project root folder in Command Prompt or Terminal and execute flutter pub get command. 
flutter pub get


Step 3
 Open your project’s main.dart file and import material.dart and intl.dart package.
import 'package:intl/intl.dart';

Step 4
You can Add Datepicker Code:
class DatePicker extends StatefulWidget {

  DatePickerWidget createState() => DatePickerWidget();

}

class DatePickerWidget extends State {

  DateTime selectedDate = DateTime.now() ;

  var customFormat = DateFormat('dd-MM-yyyy');

  Future<Null> showPicker(BuildContext context) async {
    final DateTime picked = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2018),
        lastDate: DateTime(2101));

    if (picked != null && picked != selectedDate)
      setState(() {
        selectedDate = picked;
      });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[

            Text('${customFormat.format(selectedDate)}', style: TextStyle(fontSize: 22),),
            SizedBox(height: 20.0,),

            RaisedButton(
              onPressed: () => showPicker(context),
              child: Text('Click Here To Select Date'),
              textColor: Colors.white,
              color: Colors.blue,
              padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
            ),
          ],
        ),
      ),
    );
  }
}

Related Post