본문 바로가기
카테고리 없음

07. Flutter datatimePicker

by NaHyungMin 2022. 9. 22.

datetimePicker + dropdownItme 커스텀.

추가로 붙일거면.. 여러개 붙이면 되지 않을까 싶음.

귀찮아서 전체 코드로 올림.

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class CustomDateTimeSearchBar<T> extends StatefulWidget {
  final List<DropdownMenuItem<String>> dropdownItems;
  final T parentContext;
  final VoidFunction onPressed;
  const CustomDateTimeSearchBar({Key? key, required this.dropdownItems, required this.parentContext, required this.onPressed}) : super(key: key);

  @override
  State<CustomDateTimeSearchBar> createState() => _CustomDateTimeSearchBarState();
}

class _CustomDateTimeSearchBarState extends State<CustomDateTimeSearchBar> {
  String? selectedValue;
  String datePikerStartTime = DateFormat('yyyy-MM-dd').format(DateTime.now());
  String datePikerEndTime = DateFormat('yyyy-MM-dd').format(DateTime.now());
  final _searchTextEditController = TextEditingController();

  @override
  void initState(){
    super.initState();

    selectedValue = widget.dropdownItems.isNotEmpty ? widget.dropdownItems[0].value : "";
  }

  @override
  void dispose() {
    _searchTextEditController.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
        height: 35,
        child: Center(child: Row(
          children: <Widget> [
            OutlinedButton (
            /*style: ButtonStyle(),*/
            onPressed: () async {
              DateTime? time = await showDatePicker(
                    context: context,
                    initialEntryMode: DatePickerEntryMode.calendarOnly, //편집모드 제거
                    initialDatePickerMode: DatePickerMode.day, //날짜 선택만
                    initialDate: DateTime.now(), // 초깃값
                    firstDate: DateTime(2022), // 시작일
                    lastDate: DateTime.now(), // 마지막일
                  );

              setState(() {
                if(time != null) {
                  datePikerStartTime = DateFormat('yyyy-MM-dd').format(time);
                }
              });
            },
            child: const Text('시작 날짜', style: TextStyle(color: Colors.blue, fontSize: 15.0),
            ))
            , const SizedBox(width: 10,)
            , Text(
                datePikerStartTime
                , style: const TextStyle(color: Colors.white)
                , textAlign: TextAlign.center,
            )
            , const SizedBox(width: 10,)
            , OutlinedButton (
              /*style: ButtonStyle(),*/
                onPressed: () async {
                  DateTime? time = await showDatePicker(
                    context: context,
                    initialEntryMode: DatePickerEntryMode.calendarOnly, //편집모드 제거
                    initialDatePickerMode: DatePickerMode.day, //날짜 선택만
                    initialDate: DateTime.now(), // 초깃값
                    firstDate: DateTime(2022), // 시작일
                    lastDate: DateTime.now(), // 마지막일
                  );

                  setState(() {
                    if(time != null) {
                      datePikerEndTime = DateFormat('yyyy-MM-dd').format(time);
                    }
                  });
                },
                child: const Text('시작 날짜', style: TextStyle(color: Colors.blue, fontSize: 15.0),
                ))
            , const SizedBox(width: 10,)
            , Text(
              datePikerEndTime
              , style: const TextStyle(color: Colors.white)
              , textAlign: TextAlign.center,
            )
            , const SizedBox(width: 10,)
             , Flexible(
                child: TextField(
                    controller: _searchTextEditController,
                    decoration: const InputDecoration(
                    )
                )
            )
            , DropdownButtonHideUnderline(
                  child: DropdownButton(
                    iconSize: 24,
                    style: const TextStyle(color: Colors.white),
                    alignment: Alignment.center,
                    value: selectedValue!.isNotEmpty ? selectedValue : widget.dropdownItems[0].value,
                    items: widget.dropdownItems,
                    onChanged: (String? value) {
                      widget.parentContext.setState(() {
                        selectedValue = value!;
                      });
                    },
                  ),
                )
            , IconButton(
                onPressed: () => {
                  widget.onPressed(datePikerStartTime
                      , datePikerEndTime
                      , _searchTextEditController.text
                      , widget.dropdownItems.firstWhere((element) => element.value == selectedValue))
                },
                icon: const Icon(Icons.search),
              )
          ],
        )
        )
    );
  }
}

typedef VoidFunction = void Function(String datePikerStartTime, String datePikerEndTime, String textValue, DropdownMenuItem dropdownMenuItem);

 

@override
Widget build(BuildContext context) {
  isServiceInitialize = true;

  return Column(
    children: [
      CustomDateTimeSearchBar(parentContext: this, dropdownItems: _getDropdownItems(), onPressed: (datePikerStartTime, datePikerEndTime, textValue, dropdownMenuItem) => {
         //callback
      })
    ],
  );
}


 List<DropdownMenuItem<String>> _getDropdownItems() {
    List<DropdownMenuItem<String>> menuItems = [
      const DropdownMenuItem(value: "name", child: Text("상호")),
    ];

    return menuItems;
  }

 

한국어 처리

dependencies:
  flutter:
    sdk: flutter

  flutter_localizations:
    sdk: flutter

 

Main

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(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: defaultColorScheme,
        primarySwatch: Colors.blue,
      ),
      home: const LoginPage(title: 'Login UI'),
         localizationsDelegates: const [
            GlobalMaterialLocalizations.delegate,
            GlobalCupertinoLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
          ],
          supportedLocales: const [
          /*Locale('en', 'US'),*/
          Locale('ko', 'KO'),
          ],
    );
  }
}