Flutter/UI

[Flutter] DatePicker , TimePicker

찌김이 2022. 7. 30. 22:20
728x90
반응형

  • 간단한 날짜, 시간 선택할 때 사용되는 피커 입니다. 역시 구현하기 아주아주아주 쉽습니다.

 

1. DatePicker

showDatePicker(
  context: context,
  initialDate: DateTime.now(),
  firstDate: DateTime(2022, 6, 22),
  lastDate: DateTime(2022, 8, 22),
).then((DateTime? value) => print('value = $value'));

 

2. TimePicker

showTimePicker(
  context: context,
  initialTime: TimeOfDay(hour: 22, minute: 10),
);

 

3. CupertinoDatePicker

showModalBottomSheet(
    context: context,
    builder: (_) {
      return SizedBox(
        height: 300.0,
        child: Column(
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                CupertinoButton(
                  child: const Text(
                    'Cancel',
                    style: TextStyle(
                      color: Colors.red,
                    ),
                  ),
                  onPressed: () => Navigator.pop(context),
                ),
                CupertinoButton(
                  child: const Text(
                    'Done',
                  ),
                  onPressed: () => Navigator.pop(context),
                ),
              ],
            ),
            CupertinoTimerPicker(
              onTimerDurationChanged: (value) {
                print('value = $value');
              },
            ),
          ],
        ),
      );
    });

 

4. CupertinoTimePicker

showModalBottomSheet(
    context: context,
    builder: (BuildContext context) {
      return SizedBox(
        height: 300.0,
        child: Column(
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                CupertinoButton(
                  child: const Text(
                    'Cancel',
                    style: TextStyle(
                      color: Colors.red,
                    ),
                  ),
                  onPressed: () => Navigator.pop(context),
                ),
                CupertinoButton(
                  child: const Text(
                    'Done',
                  ),
                  onPressed: () => Navigator.pop(context),
                ),
              ],
            ),
            SizedBox(
              height: 220.0,
              child: CupertinoDatePicker(
                initialDateTime: DateTime.now(),
                maximumDate: DateTime(2022, 12, 31),
                minimumYear: 2021,
                maximumYear: 2022,
                mode: CupertinoDatePickerMode.date,
                onDateTimeChanged: (DateTime value) {},
              ),
            ),
          ],
        ),
      );
    });

 

5. 한글 처리

  • pubspec.yaml 에 flutter_localizations 를 추가 합니다.
  • 그리고 MaterialApp 내부에 localizationDelegates 와 supportedLocaled 를 추가해주면 한글처리 완료입니다.
dependencies:
  flutter_localizations:
    sdk: flutter
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
    	
        // 한글처리
        localizationsDelegates: [
          GlobalMaterialLocalizations.delegate,
          GlobalCupertinoLocalizations.delegate
        ],
        supportedLocales: [
          Locale('ko', 'KR'),
        ],
        //////
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: HomeScreen(),
    );
  }
}

 

  • 예시 전체 코드 입니다.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class PickerSampleScreen extends StatelessWidget {
  const PickerSampleScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Picker Sample'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          DialogOpenButton(
            openDialog: () => datePickerDialog(context),
            btnName: 'DatePicker Dialog',
          ),
          DialogOpenButton(
            openDialog: () => timePickerDialog(context),
            btnName: 'TimePicker Dialog',
          ),
          DialogOpenButton(
            openDialog: () => cupertinoDatePickerDialog(context),
            btnName: 'CupertinoDatePicker Dialog',
          ),
          DialogOpenButton(
            openDialog: () => cupertinoTimerPickerDialog(context),
            btnName: 'CupertinoTimerPicker Dialog',
          ),
        ],
      ),
    );
  }

  datePickerDialog(BuildContext context) {
    showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(2022, 6, 22),
      lastDate: DateTime(2022, 8, 22),
    ).then((DateTime? value) => showSnackBar(context, '$value'));
  }

  timePickerDialog(BuildContext context) {
    showTimePicker(
      context: context,
      initialTime: TimeOfDay(hour: 22, minute: 10),
    );
  }

  cupertinoTimerPickerDialog(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (_) {
          return SizedBox(
            height: 300.0,
            child: Column(
              children: [
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    CupertinoButton(
                      child: const Text(
                        'Cancel',
                        style: TextStyle(
                          color: Colors.red,
                        ),
                      ),
                      onPressed: () => Navigator.pop(context),
                    ),
                    CupertinoButton(
                      child: const Text(
                        'Done',
                      ),
                      onPressed: () => Navigator.pop(context),
                    ),
                  ],
                ),
                CupertinoTimerPicker(
                  onTimerDurationChanged: (value) {
                    print('value = $value');
                  },
                ),
              ],
            ),
          );
        });
  }

  cupertinoDatePickerDialog(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return SizedBox(
            height: 300.0,
            child: Column(
              children: [
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    CupertinoButton(
                      child: const Text(
                        'Cancel',
                        style: TextStyle(
                          color: Colors.red,
                        ),
                      ),
                      onPressed: () => Navigator.pop(context),
                    ),
                    CupertinoButton(
                      child: const Text(
                        'Done',
                      ),
                      onPressed: () => Navigator.pop(context),
                    ),
                  ],
                ),
                SizedBox(
                  height: 220.0,
                  child: CupertinoDatePicker(
                    initialDateTime: DateTime.now(),
                    maximumDate: DateTime(2022, 12, 31),
                    minimumYear: 2021,
                    maximumYear: 2022,
                    mode: CupertinoDatePickerMode.date,
                    onDateTimeChanged: (DateTime value) {},
                  ),
                ),
              ],
            ),
          );
        });

  }

  showSnackBar(BuildContext context, String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
      ),
    );
  }
}

class DialogOpenButton extends StatelessWidget {
  final VoidCallback openDialog;
  final String btnName;

  const DialogOpenButton({
    Key? key,
    required this.openDialog,
    required this.btnName,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(
        horizontal: 20.0,
        vertical: 10.0,
      ),
      width: double.infinity,
      child: ElevatedButton(
        style: ElevatedButton.styleFrom(
          minimumSize: const Size.fromHeight(50),
        ),
        onPressed: openDialog,
        child: Text(
          btnName,
          style: const TextStyle(fontSize: 20),
        ),
      ),
    );
  }
}
728x90
반응형

'Flutter > UI' 카테고리의 다른 글

[Flutter] TextFormField  (0) 2022.09.04
[Flutter] DropdownButton , DropdownMenuItem  (0) 2022.09.03
[Flutter] TabBar , TabBarView  (0) 2022.08.10
[Flutter] BottomNavigationBar  (0) 2022.08.09
[Flutter] AlertDialog  (0) 2022.07.29