22.1 C
New York
Friday, August 19, 2022

Flutter Date Picker example

- Advertisement -

Flutter has a built-in function named showDatePicker that can help us easily implement a date picker.

Example

Preview:

The complete code with explanations in lib/main.dart:Advertisements

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Flutter Example',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  DateTime? _selectedDate;

  void _presentDatePicker() {
    // showDatePicker is a pre-made funtion of Flutter
    showDatePicker(
            context: context,
            initialDate: DateTime.now(),
            firstDate: DateTime(2020),
            lastDate: DateTime.now())
        .then((pickedDate) {
      // Check if no date is selected
      if (pickedDate == null) {
        return;
      }
      setState(() {
        // using state so that the UI will be rerendered when date is picked
        _selectedDate = pickedDate;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Example'),
      ),
      body: Column(children: [
        // Show the Date Picker when this button clicked
        ElevatedButton(
            onPressed: _presentDatePicker, child: const Text('Select Date')),

        // display the selected date
        Container(
          padding: const EdgeInsets.all(30),
          child: Text(
            _selectedDate != null
                ? _selectedDate.toString()
                : 'No date selected!',
            style: const TextStyle(fontSize: 30),
          ),
        )
      ]),
    );
  }
}

Further reading:

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.

Advertisements
- Advertisement -

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles