【Flutter】TextFieldでDatePickerを使う

file
file

ソースコード

// コントローラーが必要
TextEditingController _date;

TextField(
  controller: _date,
  textInputAction: TextInputAction.next,
  enabled: enabled,
  keyboardType: TextInputType.number,
  decoration: InputDecoration(
    border: OutlineInputBorder(),
    hintText: '日付',
    // inputの端にカレンダーアイコンをつける
    suffixIcon: IconButton(
      icon: Icon(Icons.calendar_today),
      onPressed: () async {

        // textFieldがの値からデフォルトの日付を取得する
        DateTime initDate = DateTime.now();
        try {
          initDate =
              DateFormat('yyyy/MM/dd').parse(_date.text);
        } catch (_) {}

        // DatePickerを表示する
        DateTime? picked = await showDatePicker(
          context: context,
          initialDate: initDate,
          firstDate: DateTime(2016),
          lastDate: DateTime.now().add(
            Duration(days: 360),
          ),
        );

        // DatePickerで取得した日付を文字列に変換
        String? formatedDate;
        try {
          formatedDate =
              DateFormat('yyyy/MM/dd').format(picked!);
        } catch (_) {}
        if (formatedDate != null) {
          _date.text = formatedDate;
        }
      },
    ),
    // labelText: 'Password',
  ),
)

Flutter開発で知らないと損すること Flutter開発で知らないと損すること

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です