Display Date Picker in Flutter

Display Date Picker in Flutter

A date picker is a popup window that allows to select a date.

We can use showDatePicker() function to display a date picker. If the user confirms the dialog then function returns a Future that completes to the selected date. If the user cancels the dialog, null is returned.

import 'package:flutter/material.dart';

void main() => runApp(const MaterialApp(home: MyApp()));

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  DateTime _date = DateTime.now();

  _showDatePicker(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _date,
      firstDate: DateTime(1970),
      lastDate: DateTime(2050),
    );

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: const Text('Date picker')),
        body: Center(
            child: ElevatedButton(
          child: const Text('Open'),
          onPressed: () => _showDatePicker(context),
        )));
  }
}

Leave a Comment

Cancel reply

Your email address will not be published.