⏰
Flutter TimePicker の使い所
使ってみたら意外とよかった
最近時間を扱うアプリの開発に携わっているのですが、毎回、ドラムロールとか使ってましたね。
でもTimePicker使ったらいい感じのが作れた。
なぜ使おうと思ったのか?
Cloud Firestoreに、DateTime -> Timestampでデータを保存したが、日付が必要ないことに気づいた。確かに入らないな💡
数字だけでいいなら、Dartだと、Int、Firestoreだと、numberになる。
DateTime.now().hourにすれば、9:00を 9にできる。正確な時間は出せないけど。

void main() {
// 例えば、今9:00。正確には9:15だけど。
DateTime? now = DateTime.now();
print(now.hour);
}
雑なコードですが、こんな感じで保存してやればできます。
🔧ロジック
// open_time
TimeOfDay open_time = TimeOfDay.now();
// close_time
TimeOfDay close_time = TimeOfDay.now();
DateTime? now = DateTime.now();
// open_time TimePicker
Future<void> _selectOpenTime(BuildContext context) async {
final TimeOfDay? picked = await showTimePicker(
context: context,
initialTime: open_time,
);
if (picked != null && picked != open_time) {
setState(() {
open_time = picked;
});
}
}
// close_time TimePicker
Future<void> _selectCloseTime(BuildContext context) async {
final TimeOfDay? picked = await showTimePicker(
context: context,
initialTime: close_time,
);
if (picked != null && picked != close_time) {
setState(() {
close_time = picked;
});
}
}
UI側はこんな感じですね。とあるソースコードを削って作りました。お店の開店時間と閉店時間を保存する管理画面で使ったロジックですね。
Row(
children: <Widget>[
const Text('営業時間'),
const SizedBox(width: 16.0),
ElevatedButton(
onPressed: () {
_selectOpenTime(context);
},
child: const Text('開店時間'),
),
const SizedBox(width: 16.0),
Text('${open_time.hour}:${open_time.minute}'),
],
),
const SizedBox(height: 16.0),
Row(
children: <Widget>[
const Text('営業時間'),
const SizedBox(width: 16.0),
ElevatedButton(
onPressed: () {
_selectCloseTime(context);
},
child: const Text('閉店時間'),
),
const SizedBox(width: 16.0),
Text('${close_time.hour}:${close_time.minute}'),
],
),
const SizedBox(height: 16.0),
ElevatedButton(
onPressed: () async {
if (_formKey.currentState!.validate()) {
// フォームが有効な場合の処理
// 例: データベースにデータを送信
try {
final db = FirebaseFirestore.instance;
await db.collection('shop').add({
'open_time': open_time.hour,
'close_time': close_time.hour,
'created_at': Timestamp.fromDate(now!),
'updated_at': Timestamp.fromDate(now!),
});
if(mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('送信が完了しました'),
),
);
}
} on Exception catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('エラーが発生しました: $e'),
),
);
}
}
},
child: const Text('送信'),
),
[ボタン押すと表示されるUI]

感想
時間を扱うロジックを色々考えているが、TimePicker使ってみて、これはいいなと思い他にも機能の試作で使ってみたいなと思いました。
Discussion