Flutter Date Ranges

This tutorial will show you how to implement date ranges in your Flutter app using the DateRangePicker widget. 

The DateRangePicker widget is a built-in Flutter widget that allows you to select a range of dates from a calendar view. You can customize the appearance of the widget to fit the design of your app and format the selected date range as needed.

To implement a date range picker in Flutter, we will use the showDateRangePicker() function provided by the Flutter framework. This function displays a dialog box that allows the user to select a range of dates. We will also use the DateTimeRange class to represent the selected date range.


Usage:

To use the code, simply copy and paste it into your Flutter project. You can then modify the code to suit your specific needs.


Code:

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class PickerDateTimeRoute extends StatefulWidget {

  const PickerDateTimeRoute({super.key}); // Constructor for the widget

  @override
  PickerDateTimeRouteState createState() => PickerDateTimeRouteState(); // Creates the state for the widget
}


class PickerDateTimeRouteState extends State {

  String date = "-";
  DateTimeRange? selectedDateRange;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          const Spacer(flex: 10), // A spacer widget to create some space between the top of the screen and the date display

          Container(
            alignment: Alignment.center,
            width: double.infinity,
            height: 45,
            color: Colors.grey[300],
            child:
            Text(date), // Displays the date on the screen
          ),

          Align(
            alignment: Alignment.center,
            child: ElevatedButton(
                style: ElevatedButton.styleFrom(
                    elevation: 0, backgroundColor: Theme.of(context).colorScheme.primary,
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
                    padding: const EdgeInsets.symmetric(horizontal: 30)
                ),
                onPressed: selectDateTimeRange,
                child: const Text("Date Range", style: TextStyle(color: Colors.white))
            ),
          )

        ],
      ),
    );
  }

  void selectDateTimeRange() async {
    final selectedDateRange = await showDateRangePicker(
      context: context,
      saveText: "Select",
      firstDate: DateTime(2000),
      lastDate: DateTime.now(),
      builder: (BuildContext context, Widget? child) {
        return Theme(
          data: ThemeData.light().copyWith(
            colorScheme:  ColorScheme.light(
              // primary: MyColors.primary,
              primary: Theme.of(context).colorScheme.primary,
              onPrimary: Colors.white,
              surface: Colors.white,
              onSurface: Colors.black,
            ),
            //.dialogBackgroundColor:Colors.blue[900],
          ),
          child: child!,
        );
      },
    );
    if (selectedDateRange == null) {
      return;
    }

    if (mounted) {
      //selectedDateRange.start
      //selectedDateRange.end
      date = "${Utils.getFormattedDateSimple(selectedDateRange.start.millisecondsSinceEpoch)} : ${Utils.getFormattedDateSimple(selectedDateRange.end.millisecondsSinceEpoch)}";
    }
    setState(() {
      this.selectedDateRange = selectedDateRange;
    });
  }
}

// Helper class
class Utils {
  static String getFormattedDateSimple(int time) {
    DateFormat newFormat = DateFormat("MMMM dd, yyyy");
    return newFormat.format(DateTime.fromMillisecondsSinceEpoch(time));
  }
}

..


Properties:

  • selectedDateRange: A DateTimeRange object that represents the currently selected date range.
  • selectDateTimeRange(): A method that calls the showDateRangePicker method to display a date picker dialog and updates the state with the new selection.
..
Flutter Widgets,

Comments

Popular posts from this blog

Creating Beautiful Card UI in Flutter

Master Web Development with Web School Offline

Jetpack Compose - Card View