TimePicker in Flutter
In this tutorial, you will learn how to use TimePicker in Flutter with the built-in showTimePicker function. The picker returns a TimeOfDay object that you can format and display in your UI.
The example below shows a simple screen with a ListTile containing a timer icon. Tapping the icon opens the Material time picker and updates the tile with the selected time.
Screenshots
Flutter Source Code
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: MyTimeTutorial(),
title: "Time Picker Tutorial",
));
}
class MyTimeTutorial extends StatefulWidget {
@override
_MyFieldTutorialState createState() => _MyFieldTutorialState();
}
class _MyFieldTutorialState extends State<MyTimeTutorial> {
String selectedtime = "Select Time";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Time Picker Tutorial"),
),
body: Container(
child: Column(
children: [
ListTile(
title: Text("$selectedtime"),
trailing: IconButton(
icon: Icon(
Icons.timer,
color: Colors.red,
),
onPressed: () {
getshowTimePicker().then((value) {
if (value != null) {
setState(() {
selectedtime = value.format(context);
});
}
});
},
),
),
],
),
),
);
}
Future getshowTimePicker() async {
var selected = await showTimePicker(
context: context,
initialTime: TimeOfDay.now(),
);
return selected;
}
}
Frequently Asked Questions
What is showTimePicker in Flutter?
showTimePicker is a built-in Flutter function that opens a Material Design time picker dialog and returns a TimeOfDay object representing the selected time, or null if the user cancels.
How do I format the selected time in Flutter?
Call value.format(context) on the TimeOfDay returned by showTimePicker. This automatically formats the time according to the device locale, for example 10:30 PM or 22:30.
How do I set a default time in showTimePicker?
Pass TimeOfDay.now() or a custom TimeOfDay to the initialTime parameter of showTimePicker. The dialog will open with that time preselected.
How do I switch between 12-hour and 24-hour format in Flutter TimePicker?
Set the builder parameter inside showTimePicker to force 24-hour format:
builder: (context, child) {
return MediaQuery(
data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true),
child: child!,
);
}
Does showTimePicker work on both Android and iOS?
Yes. showTimePicker renders the Material Design time picker on both Android and iOS by default. On iOS, it appears with Material styling rather than the native Cupertino picker.
Conclusion
In this tutorial, you learned how to implement a TimePicker in Flutter using the built-in showTimePicker function. You used TimeOfDay.now() as the initial time, formatted the result with value.format(context), and updated the UI with setState.
Related topics: Flutter DatePicker, Flutter Material Dialogs, TimeOfDay Formatting, Flutter Stateful Widgets, Flutter ListTile, Flutter IconButton
No comments:
Post a Comment