카테고리 없음

flutter datepicker provider

햎피 2022. 7. 4. 15:37
반응형

flutter에서 datepicker를 사용해서 원하는 날짜를 선택 할 수 있다.

코드는 다음과 같다

 

screen 부분

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

  @override
  Widget build(BuildContext context) {
    return Container(
        width: 65,
        margin: EdgeInsets.fromLTRB(30, 0, 0, 0),
        child: Text(
          '종료일  ',
          style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
        ));
  }
}

class EndDateFeild extends StatelessWidget {
  EndDateFeild({Key? key}) : super(key: key);
  late TripstartModel tripstart;

  @override
  Widget build(BuildContext context) {
    tripstart = Provider.of<TripstartModel>(context);

    return Expanded(
      child: TextField(
        readOnly: true,
        onTap: () {
          Datepick(context);
        },
        controller: tripstart.endDate == ''
            ? TextEditingController(text: '')
            : TextEditingController(text: tripstart.endDate.substring(0, 10)),
        cursorColor: Colors.black,
        keyboardType: TextInputType.text,
        decoration: InputDecoration(
            isDense: true,
            contentPadding: EdgeInsets.all(7),
            border: OutlineInputBorder(),
            hintText: "종료일을 선택하세요"),
      ),
    );
  }

  void Datepick(context) {
    Future<DateTime?> selectedDate = showDatePicker(
      context: context,
      initialDate: tripstart.endDate == ''
          ? DateTime.now()
          : DateTime.parse(tripstart.endDate), //초기값
      firstDate: DateTime(2020), //시작일
      lastDate: DateTime(2025), //마지막일
      builder: (BuildContext context, Widget? child) {
        return Theme(
          data: Theme.of(context).copyWith(
            colorScheme: ColorScheme.light(
              primary:
                  Color.fromARGB(255, 195, 221, 243), // header background color
              onPrimary: Colors.black, // header text color
              onSurface: Colors.black,
            ),
            textButtonTheme: TextButtonThemeData(
              style: TextButton.styleFrom(
                primary: Colors.blue, // button text color
              ),
            ),
          ), //다크 테마
          child: child!,
        );
      },
    );

    selectedDate.then((dateTime) {
      if (dateTime == null) {
        print('날짜 설정 취소');
      } else {
        tripstart.setenddatetext(dateTime.toString().substring(0, 10));
      }
    });
  }
}

 

 

model 부분이다.

class TripstartModel extends ChangeNotifier {
  String _endDate = '';
  
  String get endDate => _endDate;

  void setenddatetext(endDate) {
    _endDate = endDate;
    notifyListeners();
  }

}

 

 

실행시켰을 때의 화면이다.

반응형