showDatePicker()를 사용하면 달력을 띄워서 날짜를 선택할 수 있습니다
import 'package:flutter/material.dart';
class Calendar extends StatefulWidget {
@override
State<Calendar> createState() => CalendarState();
}
class CalendarState extends State<Calendar> {
DateTime date = DateTime.now(); // 선택한 날짜를 입력받을 변수 선언
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: TextButton(onPressed: () async{
final selectedDate = await showDatePicker(
context: context, // 팝업으로 띄우기 때문에 context 전달
initialDate: date, // 달력을 띄웠을 때 선택된 날짜. 위에서 date 변수에 오늘 날짜를 넣었으므로 오늘 날짜가 선택돼서 나옴
firstDate: DateTime(1950), // 시작 년도
lastDate: DateTime.now(), // 마지막 년도. 오늘로 지정하면 미래의 날짜는 선택할 수 없음
);
if (selectedDate != null) {
setState(() {
date = selectedDate; // 선택한 날짜는 date 변수에 저장
});
}
}, child: Text('$date')) //출력하면 시간도 같이 출력이 되는데 날짜만 표시하고 싶으면 substring으로 잘라내면 됨
)
);
}
}
- 실행결과
※ 달력 한글로 표시하는 방법
1. pubspec.yaml의 dependencies에 flutter_localizations: sdk: flutter를 추가
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
2. main. dart에 import 'package:flutter_localizations/flutter_localizations.dart'; 를 추가.
추가가 안되면, pubspec.yaml 파일에서 intl: ^0.17.0 플러그인 추가하고 pub.get 하고 IDE 재시작
3. MyApp의 MaterialApp 안에
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: [
const Locale('ko', 'KR'),
],
를 추가.
@override
Widget build(BuildContext context) {
return GetMaterialApp(
home: LoginPage(),
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: [
const Locale('ko','KR'),
],
);
}
이렇게 하면 달력이 한글로 나오는 것을 확인할 수 있습니다.
'Flutter' 카테고리의 다른 글
[Flutter] 웹 Mixed Content 에러 쉽고 간단하게 해결하는 방법 (0) | 2023.05.05 |
---|---|
Flutter(플러터) Firebase(파이어베이스)에서 데이터 가져와서 화면으로 보여주기 (0) | 2023.04.20 |
[Flutter] 심플한 팝업 메뉴 만들기 (0) | 2023.04.04 |
[Flutter] image_picker로 사진 업로드 화면 만들기 (0) | 2023.03.28 |
Flutter GridView(그리드뷰) 사용 방법 (0) | 2023.03.26 |