flutter/examples/api/lib/material/date_picker/show_date_picker.1.dart
Jiten Patel 3e9901dac9
Fix: showDatePicker should have a simple example in the docs (#156196)
This PR introduces a basic example of how to use the `showDatePicker` function. The purpose of this PR is to simplify the onboarding process for new Flutter developers by providing a straightforward demonstration of handling the asynchronous Future returned by the showDatePicker. This will help users unfamiliar with the intricacies of asynchronous operations in Flutter.

Fixes #156157
2024-10-22 17:04:23 +00:00

67 lines
1.6 KiB
Dart

// Copyright 2014 The Flutter Authors. 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';
/// Flutter code sample for basic [showDatePicker].
void main() => runApp(const DatePickerApp());
class DatePickerApp extends StatelessWidget {
const DatePickerApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('showDatePicker Example')),
body: const Center(child: DatePickerExample()),
),
);
}
}
class DatePickerExample extends StatefulWidget {
const DatePickerExample({super.key});
@override
State<DatePickerExample> createState() => _DatePickerExampleState();
}
class _DatePickerExampleState extends State<DatePickerExample> {
DateTime? selectedDate;
Future<void> _selectDate() async {
final DateTime? pickedDate = await showDatePicker(
context: context,
initialDate: DateTime(2021, 7, 25),
firstDate: DateTime(2021),
lastDate: DateTime(2022),
);
setState(() {
selectedDate = pickedDate;
});
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
spacing: 20,
children: <Widget>[
Text(
selectedDate != null
? '${selectedDate!.day}/${selectedDate!.month}/${selectedDate!.year}'
: 'No date selected',
),
OutlinedButton(
onPressed: _selectDate,
child: const Text('Select Date'),
),
],
);
}
}