Make range date picker in flutter
Asked Answered
D

3

7

I am trying to make a date range picker like this ,date picker start with on value (today value) then user select the range he need ,in flutter finally I found this package.

But I can't open it when I click on the button as date picker.

I trayed to use another package date range picker but it doesn't help me! enter image description here

Doubletongued answered 13/12, 2020 at 11:56 Comment(0)
F
16

Flutter has now an inbuilt date range picker below is an example of using it

IconButton(
        onPressed: () async {
          final picked = await showDateRangePicker(
            context: context,
            lastDate: endDate,
            firstDate: new DateTime(2019),
          );
          if (picked != null && picked != null) {
            print(picked);
            setState(() {
              startDate = picked.start;
              endDate = picked.end;
//below have methods that runs once a date range is picked 
              allWaterBillsFuture = _getAllWaterBillsFuture(
                  picked.start.toIso8601String(),
                  picked.end
                      .add(new Duration(hours: 24))
                      .toIso8601String());
            });
          }
        },
        icon: Icon(
          Icons.calendar_today,
          color: Colors.white,
        ),
      ),
Fredfreda answered 19/2, 2021 at 0:19 Comment(0)
M
1

There's a package specifically built for that purpose, date_range_picker To install it, you should add the following line under dependecies in the pubspec.yaml file:

date_range_picker: ^1.0.5

You should then import the package at the top of the file of the Widget you would like to use the function:

import 'package:date_range_picker/date_range_picker.dart' as DateRangePicker;

Then, you could use the package as follows:

new MaterialButton(
    color: Colors.deepOrangeAccent,
    onPressed: () async {
      final List<DateTime> picked = await DateRagePicker.showDatePicker(
          context: context,
          initialFirstDate: new DateTime.now(),
          initialLastDate: (new DateTime.now()).add(new Duration(days: 7)),
          firstDate: new DateTime(2015),
          lastDate: new DateTime(2020)
      );
      if (picked != null && picked.length == 2) {
          print(picked);
      }
    },
    child: new Text("Pick date range")
)

This is a full example on how you could use it:

import 'package:flutter/material.dart';
import 'package:date_range_picker/date_range_picker.dart' as DateRagePicker;

void main() {
  runApp(MaterialApp(home: HomeScreen(), title: 'Flutter Date Range Example'));
}

class HomeScreen extends StatefulWidget {
  HomeScreen({Key key}) : super(key: key);

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

class _HomeScreenState extends State<HomeScreen> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: MaterialButton(
            color: Colors.deepOrangeAccent,
            onPressed: () async {
              final List<DateTime> picked = await DateRagePicker.showDatePicker(
                  context: context,
                  initialFirstDate: new DateTime.now(),
                  initialLastDate:
                      (new DateTime.now()).add(new Duration(days: 7)),
                  firstDate: new DateTime(2015),
                  lastDate: new DateTime(2020));
              if (picked != null && picked.length == 2) {
                print(picked);
              }
            },
            child: new Text("Pick date range")),
      ),
    );
  }
}
Millner answered 13/12, 2020 at 13:27 Comment(3)
I copied this code but i get this excpetion on clicking button Exception has occurred. _AssertionError ('package:date_range_picker/date_range_picker.dart': Failed assertion: line 1280 pos 10: '!initialLastDate.isAfter(lastDate)': initialDate must be on or before lastDate)Doubletongued
and how can i make the initial selected date today only and date range detected when user selecte date rangeDoubletongued
@amira syam Did you solve this error. I am using showDateRangePickerFreemason
F
1

Here, I'm using Flutter inbuilt date range picker, where you should initially give the start and end date, to display the selected range used two elevated buttons where the date range will be shown.in setState, if you click cancel in daterange picker popup, the initial date range will be assigned.

import 'package:flutter/material.dart';

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

  @override
  State<DateRangeWidget> createState() => _DateRangeWidgetState();
}

class _DateRangeWidgetState extends State<DateRangeWidget> {
  DateTimeRange dateRange = DateTimeRange(
    start: DateTime(2021, 11, 5),
    end: DateTime(2022, 12, 10),
  );
  @override
  Widget build(BuildContext context) {
    final start = dateRange.start;
    final end = dateRange.end;

    return Column(children: [
      const Text(
        'Date Range',
        style: TextStyle(fontSize: 16),
      ),
      Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            child: ElevatedButton(
              child: Text(
                '${start.year}/${start.month}/${start.day}',
              ),
              onPressed: pickDateRange,
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 20),
            child: ElevatedButton(
              child: Text(
                '${end.year}/${end.month}/${end.day}',
              ),
              onPressed: pickDateRange,
            ),
          ),
        ],
      )
    ]);
  }

  Future pickDateRange() async {
    DateTimeRange? newDateRange = await showDateRangePicker(
      context: context,
      initialDateRange: dateRange,
      firstDate: DateTime(2019),
      lastDate: DateTime(2023),
    );
    setState(() {
      dateRange = newDateRange ?? dateRange;

      // if (newDateRange == null) return;
      // setState(() => dateRange = newDateRange);
    });
  }
}
  [1]: https://i.sstatic.net/h1HIN.png
Forestforestage answered 24/2, 2022 at 15:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.