[flutter] 플러터 DatePicker에 특정 날짜 표시하기
아래는 initialDate
를 사용하여 DatePicker에 특정 날짜를 표시하는 방법을 보여주는 예제 코드입니다.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
DateTime _selectedDate = DateTime.now();
Future<void> _selectDate(BuildContext context) async {
final DateTime picked = await showDatePicker(
context: context,
initialDate: _selectedDate,
firstDate: DateTime(2015, 8),
lastDate: DateTime(2101),
);
if (picked != null && picked != _selectedDate)
setState(() {
_selectedDate = picked;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter DatePicker 예제'),
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text("${_selectedDate.toLocal()}".split(' ')[0]),
SizedBox(
height: 20.0,
),
ElevatedButton(
onPressed: () => _selectDate(context),
child: Text('날짜 선택'),
),
],
),
),
);
}
}
위의 예제 코드에서는 initialDate
를 사용하여 DatePicker를 열 때 특정 날짜로 설정되도록 하였습니다.