[Flutter]時刻を選択できるようにするには?

Flutter

どうも、ちょげ(@chogetarou)です。

Flutterで時刻を選択できるようにするには、どうしたらいいのでしょうか?

スポンサーリンク

方法

時刻を選択するには、「TimePicker」を使います。

「TimePicker」は、次のような流れで使います。

  1. 選択した時刻を保持する変数を用意
  2. 「TimePicker」を表示し、時刻を選択させる関数を用意
  3. タップやスワイプなどのトリガーに関数を設定

Step1

まず、選択した時刻を保持する変数を用意します。

TimeOfDay? selectedTime;

変数の型は、「TimeOfDay?」にします。

Step2

次に、「TimePicker」を表示し、時刻を選択させるための関数を用意します。

  Future _pickTime(BuildContext context) async {
    final initialTime = TimeOfDay(hour: 10, minute: 0);

//TimePickerの表示
    final newTime =
        await showTimePicker(context: context, initialTime: initialTime);

    if (newTime != null) {
//選択した時刻を最初に用意した変数に格納
      setState(() => selectedTime = newTime);
    } else {
      return;
    }
  }

「TimePicker」は、「showTimePicker関数」を使って表示します。

この関数には、「await」を指定し、ユーザーが選択した後に処理を再開できるようにしています。

「showTimePicker関数」には、「context引数」と「initialTime引数」を設定する必要があります。

「initialTime引数」は、時刻の初期値となるものです。

その他の引数では、「TimePicker」の設定をすることが出来ます。

Step3

最後に、ボタンやスワイプなどのトリガーに、用意した関数を指定します。

ElevatedButton(
              onPressed: () => _pickTime(context),
              child: const Text("Pick Date"))

ここではボタンを使っていますが、他のトリガーでも同じように指定します。

これで時刻ができるようになります。

全体のコード

class Sample extends StatefulWidget {
  Sample({Key? key}) : super(key: key);

  @override
  _SampleState createState() => _SampleState();
}

class _SampleState extends State<Sample> {
  TimeOfDay? selectedTime;

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(selectedTime != null
              ? "${selectedTime!.hour}:${selectedTime!.minute}"
              : "Time"),
          SizedBox(
            height: 20,
          ),
          ElevatedButton(
              onPressed: () => _pickTime(context),
              child: const Text("Pick Date"))
        ],
      ),
    );
  }

  Future _pickTime(BuildContext context) async {
    final initialTime = TimeOfDay(hour: 10, minute: 0);

    final newTime =
        await showTimePicker(context: context, initialTime: initialTime);

    if (newTime != null) {
      setState(() => selectedTime = newTime);
    } else {
      return;
    }
  }
}

コメント

タイトルとURLをコピーしました