Make writing a habit together! This is my first day to participate in the “Gold Digging Day New Plan · April More text challenge”, click to see the details of the activity. Compare the Flutter date picker libraries

A date picker is a useful addition to the UI, making it easy for your application users to select dates from the calendar. Whether you add a date of birth field to a sign-up form or provide users with time slots to book, you can use the date picker library to simplify the process.

In this tutorial, we will explore the three popular Date pickers libraries for Flutter, Flutter Datetime Picker, Flutter Date Range Picker, and date_time_picker. We’ll examine the capabilities of each library and install each library in a simple mobile application.

To follow this tutorial, you will need:

  • The Flutter is installed on your machine
  • Flutter Basics
  • Familiar with the Dart
  • Xcode or Android Studio is installed on your machine
  • An iOS or Android emulator for testing
  • A Code editor, VS Code

Let’s get started!

Flutter date and time picker

The Flutter date and time picker is easy to customize and supports date and time selection in multiple languages. The Flutter Datetime Picker is simple to install and provides a stylish, user-friendly interface.

To build our date Picker using the Flutter Datetime Picker, we will initialize a new Flutter application and install a copy of the Flutter Datetime Picker package. If you’re on a Mac, navigate to your working directory from the terminal, or to the command prompt if you’re on Windows. Run the following code:

flutter create date_picker_app
Copy the code

After initialization, navigate to the date_picker_app folder and run the following command to install the Flutter Datetime Picker package:

flutter pub add flutter_datetime_picker
Copy the code

Now, let’s build a basic date and time picker that displays once the user selects a button. Add the following code to main.dart:

TextButton(
    onPressed: () {
        DatePicker.showDatePicker(context,
                              showTitleActions: true,
                              minTime: DateTime(2018.3.5),
                              maxTime: DateTime(2019.6.7), onChanged: (date) {
                            print('change $date');
                          }, onConfirm: (date) {
                            print('confirm $date');
                          }, currentTime: DateTime.now(), locale: LocaleType.en);
    },
    child: Text(
        'show date time picker',
        style: TextStyle(color: Colors.blue),
    ));
Copy the code

In the code above, we showDatePicker uses TextButton whenever the user clicks the show date and time picker button. Recall that the package supports multiple languages; In our example, we set the currentTime locale to localetype.en and set the default language to English.

Next, open your Android or iOS emulator and run the application using the following command:

flutter run 
Copy the code

Your application should look like the following:

The Flutter Datetime Picker also supports themes, allowing you to customize colors to achieve the look and feel you want. Let’s add a custom style Date to our application by creating a new component with buttonText Inscription. In the main.dart file, add the following code to the new buttonText component:

import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: new ThemeData(
        primarySwatch: Colors.green,
      ),
      home: newHomePage(), ); }}class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Datetime Picker'),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            //new buttonText starts
            TextButton(
                onPressed: () {
                  DatePicker.showDatePicker(context,
                      showTitleActions: true,
                      minTime: DateTime(2018.3.5),
                      maxTime: DateTime(2019.6.7),
                      theme: DatePickerTheme(
                          headerColor: Colors.grey,
                          backgroundColor: Colors.green,
                          itemStyle: TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                              fontSize: 18),
                          doneStyle:
                              TextStyle(color: Colors.white, fontSize: 16)),
                      onChanged: (date) {
                    print('change $date in time zone ' +
                        date.timeZoneOffset.inHours.toString());
                  }, onConfirm: (date) {
                    print('confirm $date');
                  }, currentTime: DateTime.now(), locale: LocaleType.en);
                },
                child: Text(
                  'Date with theme',
                  style: TextStyle(color: Colors.green),
                )),
              //new buttonText ends.],),),); }}Copy the code

Restart your application by pressing R on the terminal or at a command prompt. Now, when you click the date button with a theme, your application should look like the screen capture below:

Flutter date range selector

With the Flutter date range picker, users can easily select a single date, multiple dates, or a range of dates. To limit date selection, you can set a minimum or maximum number of days for the user to select. You can also mask or limit days to prevent users from selecting them.

To create a date picker using the Flutter date range picker, first install the widget by running the following code on a terminal or command prompt:

flutter pub add syncfusion_flutter_datepicker
Copy the code

After installation, main.dart updates the file with the following code:

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:syncfusion_flutter_datepicker/datepicker.dart';
void main() {
  return runApp(MyApp());
}
/// My app class to display the date range picker
class MyApp extends StatefulWidget {
  @override
  MyAppState createState() => MyAppState();
}
/// State for MyApp
class MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
        home: Scaffold(
            appBar: AppBar(
              title: const Text('Date Range picker'),
            ),
            body: Stack(
              children: <Widget>[
                Positioned(
                  left: 0,
                  right: 0,
                  top: 0,
                  height: 80,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                  ),
                ),
                Positioned(
                  left: 0,
                  top: 80,
                  right: 0,
                  bottom: 0,
                  child: SfDateRangePicker(
                    selectionMode: DateRangePickerSelectionMode.range,
                    initialSelectedRange: PickerDateRange(
                        DateTime.now().subtract(const Duration(days: 4)),
                        DateTime.now().add(const Duration(days: 3))),),)],))); }}Copy the code

The first argument, the SfDateRangePicker class, selectionMode, indicates that the input date is displayed on it. In this case, we show range, but you can choose to show the single date.

The second parameter initialSelectedRange is responsible for the date selected by default. We use the DateTime class to create the date range.

Your application should look like the following screen capture:

In just a few lines of code, we’ve created an organized date picker with a pleasing UI.

Flutter date_time_picker

The date_time_picker is a Flutter widget that uses text form fields to display the date and time.

Install the package by running the following code from a terminal or command prompt:

flutter pub add date_time_picker
Copy the code

To create a simple date picker with Flutter, date_time_picker, simply add the following code:

DateTimePicker(
  initialValue: ' ',
  firstDate: DateTime(2000),
  lastDate: DateTime(2100),
  dateLabelText: 'Date',
  onChanged: (val) => print(val),
  validator: (val) {
    print(val);
    return null;
  },
  onSaved: (val) => print(val),
);
Copy the code

In the code snippet above, we use the DateTimepicker class. InitialValue Saves the value of the date text field. FirstDate is the year the calendar starts and lastDate is the last year it ends.

Now that we know the basics of the date_time_picker package, let’s build and customize our own. To create the date and time picker dialog, replace the code in the main.dart file with the following:

import 'package:date_time_picker/date_time_picker.dart';
import 'package:flutter/material.dart';

void main() {
  return runApp(MyApp());
}
/// My app class to display the date range picker
class MyApp extends StatefulWidget {
  @override
  MyAppState createState() => MyAppState();
}
/// State for MyApp
class MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
            appBar: AppBar(
              title: const Text('Date Range picker'),
            ),
            body: Stack(
              children: <Widget>[
                DateTimePicker(
                  initialValue: ' ',
                  firstDate: DateTime(2000),
                  lastDate: DateTime(2100),
                  dateLabelText: 'Date',
                  onChanged: (val) => print(val),
                  validator: (val) {
                    print(val);
                    return null;
                  },
                  onSaved: (val) => print(val), ) ], ))); }}Copy the code

Your application should look like the following screen capture:

When you click on the Date text field, you should have a calendar dialog box that looks like the following screen capture:

conclusion

After exploring three popular Flutter date pickers libraries, you should now be able to select the one that best suits your needs and install it in your own application. Although these tools are similar, the right choice may depend on the uniqueness of your project.

For example, if your application uses a language other than English, it might be better to use the Flutter Datetime Picker. To easily limit Date selection, the Flutter Date Range Picker is a good choice.

All three provide organized, engaging, and customizable interfaces that you can set up in a matter of minutes.

Today’s content is introduced here, if you like, you can support it