You are currently viewing Flutter DatePicker Tutorial and Examples

Flutter DatePicker Tutorial and Examples

Flutter DatePicker Tutorial and Example

In this piece we see how to use DatePicker to pick and show dates using a nice bottomsheet in flutter.

The ability to pick dates is one of the most important aspects of any user interface framework. And certainly Flutter
is a framework for android applications development. Flutter allows us be pick dates with various libraries out there we can use. One such is the flutter_date_picker which we use in this project.

Through it we will be able to pick dates and show in a snackbar.

Flutter DatePicker

Flutter DatePicker

Video tutorial(ProgrammingWizards TV Channel)

Well we have a video tutorial as an alternative to this. If you prefer tutorials like this one then it would be good you subscribe to our YouTube channel. Basically we have a TV for programming where do daily tutorials especially android.

What is Flutter Date Picker

It's a Cupertino styled date picker component which works on both ios and android. This is a third party library we are using and will allow us to easily implement a nice beautiful datepicker.

You can find it here.

Here are the files we explore:

  1. pubspec.yaml
  2. lib/main.dart

(a). pubspec.yaml

This is where we add our dependencies:

name: mr_datetimepicker
description: A new Flutter project.
dependencies:
  flutter:
    sdk: flutter
  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  flutter_date_picker: ^0.1.2
dev_dependencies:
  flutter_test:
    sdk: flutter

You can see we've used the flutter_date_picker library.

(b). main.dart

import 'package:flutter/material.dart';
import 'package:flutter_date_picker/flutter_date_picker.dart';
// Our MyApp class.
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(primarySwatch: Colors.blue,),
      home: Home(),
    );
  }
}
// A widget that has mutable state.
class Home extends StatefulWidget {
  //Creates the mutable state for this widget at a given location in the tree.
  //We override this method to return a newly created instance of our <code>_HomeState
  @override
  _HomeState createState() => _HomeState();
}
//Our HomeState
//State is information that can be read synchronously when the widget is built
//and might change during the lifetime of the widget.
class _HomeState extends State<Home> {
  //GlobalKey is allows us create a key that is unique across the entire app.
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  //VoidCallback is a Signature of callbacks that have no arguments and return no data
  // defined in the dart.ui package
  VoidCallback _showBottomSheetCallback;
  //boolean value
  bool showDatePicker = false;
  //initState will be called when this object is inserted into the tree.
  @override
  void initState() {
    super.initState();
    _showBottomSheetCallback = _showBottomSheet;
  }
  //let's show a SnackBar at the bottom of the scaffold.
  void _snackBar(String text) {
    //GlobalKey gives us the currentState property which allows invoke the showSnackBar()
    // hence showing State for the widget in the tree that currently has this global key.
    _scaffoldKey.currentState.showSnackBar(SnackBar(content: Text(text)));
  }
  //our private _showBottomSheet method
  _showBottomSheet() {
    //Again Notify the framework that the internal state of this object has changed.
    setState(() {
      // disable the button
      _showBottomSheetCallback = null;
    });
    //show bottom sheet
    _scaffoldKey.currentState
        .showBottomSheet<Null>(
          (BuildContext context) {
            return DateOfBirth(
              key: dobKey,
              setDate: _setDateOfBirth,
            );
          },
        )
        .closed
        .whenComplete(() {
          //State.mounted() returns a boolean indicating whether this State object
          //is currently in a tree.
          if (mounted) {
            // setState will notify the framework that the internal state of
            // this object has changed
            setState(() {
              // re-enable the button
              _showBottomSheetCallback = _showBottomSheet;
            });
          }
        });
  }
  void _setDateOfBirth() {
    Navigator.of(context).pop();
    _snackBar(dobKey.currentState.dobStrMonth +
        ' ${dobKey.currentState.dobDate}' +
        ' ${dobKey.currentState.dobYear}');
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        backgroundColor: Color(0xFFF98495),
        title: Text('Mr DatePicker'),
      ),
      body: Container(
        padding: EdgeInsets.all(10.0),
        alignment: Alignment.topCenter,
        child: RaisedButton(
          color: Color(0xFFF98495),
          child: Text('Choose Date'),
          onPressed: () {
            _showBottomSheet();
          },
        ),
      ),
    );
  }
}
//Top level main method
void main() => runApp(MyApp());

Leave a Reply