Skip to content

Instantly share code, notes, and snippets.

@wisnuwiry
Created February 11, 2022 03:54
Show Gist options
  • Save wisnuwiry/cdf2e585cbc6633bffd3efe749e7cc62 to your computer and use it in GitHub Desktop.
Save wisnuwiry/cdf2e585cbc6633bffd3efe749e7cc62 to your computer and use it in GitHub Desktop.
Flutter Example Select Date Range Picker with showDateRangePicker
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
const MyHomePage({
Key? key,
required this.title,
}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
DateTimeRange? _selectedDates;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Start Date: '
'${_formatDateToString(_selectedDates?.start)} '
'sampai '
'${_formatDateToString(_selectedDates?.end)}'),
),
body: Center(
child: ElevatedButton(
child: const Text('Pilih Tanggal'),
onPressed: _showSelectDatePicker,
),
),
);
}
String _formatDateToString(DateTime? date) {
if (date == null) return '-';
return '${date.year}:${date.month}:${date.day}';
}
Future _showSelectDatePicker() async {
final result = await showDateRangePicker(
context: context,
initialDateRange: _selectedDates,
firstDate: DateTime(2000), // tanggal awal yang diperbolehkan di pilih
lastDate: DateTime(2100), // tanggal akhir yang diperbolehkan di pilih
);
if (result != null) {
setState(() {
_selectedDates = result;
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment