DateRange(selecting start and end date)

1.add below package for date fromats

dependencies:
  intl: ^0.17.0

url: https://pub.dev/packages/intl

Example Code:

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

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

  @override
  State<DateRanges> createState() => _DateRangesState();
}

class _DateRangesState extends State<DateRanges> {
  DateTimeRange dateTimeRange = DateTimeRange(start: DateTime.now(), end: DateTime.now().add(Duration(days: 1)));

  @override
  Widget build(BuildContext context) {
    final start = dateTimeRange.start;
    final end = dateTimeRange.end;
    final difference = dateTimeRange.duration;
    return SafeArea(
        child: Scaffold(
            body: Column(
              mainAxisAlignment: MainAxisAlignment.center,
                children: [
                Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                ElevatedButton(onPressed:() => pickDateRange(),
        child: Text(DateFormat('yyyy/MM/dd').format(start))),
    ElevatedButton(
        onPressed: () =>  pickDateRange(),
        child: Text(DateFormat('yyyy/MM/dd').format(end))),
    ],
    ),
                  SizedBox(height: 50.0,),
                  Text("${difference.inDays} days difference", style: TextStyle(color: Colors.black),)
    ],
    ),
    )
    ,
    );
  }

  Future pickDateRange() async {
    DateTimeRange newDateRange = await showDateRangePicker(
        context: context,
        initialDateRange: dateTimeRange,
        firstDate: DateTime(1900),
        lastDate: DateTime(2100)
    );
    if(newDateRange == null) return;
    setState(() {
      dateTimeRange = newDateRange;
    });
  }
}


Sign In or Register to comment.