Flutter - Creating Time Picker Using Material Design - GeeksforGeeks

21 Jun, 2021
Time Picker is a UI component that controls or lets the selection of time in either 24-hours format or AM/PM format. Mainly is job is to ease out the process of time selection and to ensure that the user is picking or selecting a valid time in the application. This can be used in the applications such as alarm, stop-watch or in any other scenario where time selection is required.  In native android time picker is available in two modes, the first one is the clock, where the user can select the time from the clock itself first selecting the house and then the minutes. And another mode is the spinner mode where the user can manually type in the time or scroll through the spinner. Flutter makes it very easy to implement both of these as it out of the box gives us both modes without any additional efforts. So in this article, we are going to see how to implement a time picker in flutter.
We will be using VS Code IDE for this project, you can also use Android Studio or any other IDE. The only package that will be used in this app is material.dart.  Some of the concepts that will be used while developing this app are listed below:
Using Material design to build UI on the screen.
Using Stateful Widget.
Logic building through dart function.
Step 1: The first step is going to be simple.
Here we have first imported the material.dart package through which the UI will be built in the following steps. Flutter by default takes material design into use. The material design system is created by Google. Although flutter gives us full flexibility to customize the design either as per our will or by using Cupertino widgets which are an alternative to material design.
Then we have initialized the main function which is the starting point of this flutter app. Inside the main function, we have the runApp method. The main job of this method is to inflate the given widget and attach it to the screen. The widgets to be inflated will be described in the MyApp class in the following steps.
Dart
import 'package:flutter/material.dart';  // Main function which starts the appvoid main() {  runApp(MyApp());}
Step 2:  In this step, we have performed three main things.
Here MyApp class which is going to hold all the widgets of this app is extended as the Stateless widget which would not require a mutable state.
Then overriding the already present info of the Stateless widgets we have provided our own description of the same.
Following we have used the build method. This describes the part of the user interface represented by this widget.  And also controls the location of the widgets to be painted on the screen. Inside this, we have described the title, theme  & extending class of our MaterialApp.
Dart
class MyApp extends StatelessWidget {      // This widget is the root of your application.  @override  Widget build(BuildContext context) {    return MaterialApp(      title: 'Flutter Demo',      theme: ThemeData(                  // This is the theme of your application.        primarySwatch: Colors.green,      ),      home: MyHomePage(title: 'GeeksForGeeks'),    );  }}
Step 3: In step three we have the following things:
This widget is the home page of your application. It is stateful, meaning that it has a State object (defined below) that contains fields that affect how it looks.
This class is the configuration for the state. It holds the values (in this case the title) provided by the parent (in this case the App widget) and used by the build method of the State. Fields in a Widget subclass are always marked “final”.
Dart
class MyHomePage extends StatefulWidget {  MyHomePage({Key key, this.title}) : super(key: key);    // This widget is the home of this app which is Stateful  final String title;    @override  _MyHomePageState createState() => _MyHomePageState();}
Step 4: In this step, we build the logic for the time selection.
We have the class TimeofDay class which is representing a time during the day, independent of the date that day might fall on or the time zone. The time is represented by [hour] and [minute] pair. Once created, both values cannot be changed. By using this class we will create time of the day which will get selected by the UI selector. TimeOfDay.now() creates a time base on the current time. This sets the hour and the minute to be the current time.
Then in the Future we have used the showTimePicker function which will show a material-designed time picker on the screen for the user to select time.setState function tells the system that something in the state of the object was changed. The time gets selected by it is set equal to the picked time which is then printed on the console.
Dart
class _MyHomePageState extends State<MyHomePage> {  TimeOfDay _time = TimeOfDay.now();  TimeOfDay picked;    Future<Null> selectTime(BuildContext context) async {    picked = await showTimePicker(      context: context,      initialTime: _time,    );    setState(() {      _time = picked;        print(picked);    });  }      ....
Step 5: In this step, we have finalized the app by building the UI for the logic, that was curated in the previous step.
In the MyHomePage class, we have the build method which is returned whenever the user will select the time because it will call the setState function.
Following is the Scaffold widget which is holding all the widgets displayed on the screen such as the AppBar which is on the top of the screen and Center widget which is holding the body of the app. In the Center widget, we have the IconButton and Text separated by the SizedBox. 
Whenever the alarm icon is pressed selectTime function gets triggered which pops up a time picker.
Dart
....      @override  Widget build(BuildContext context) {        // This method is rerun every time setState is called.        return Scaffold(      appBar: AppBar(                  // Here we take the value from the MyHomePage object that was created by        // the App.build method, and use it to set our appbar title.        title: Text(widget.title),      ),      body: Center(                  // Center is a layout widget. It takes a single child and positions it        // in the middle of the parent.        child: Column(          mainAxisAlignment: MainAxisAlignment.center,          children: [            IconButton(              iconSize: 80,              icon: Icon(                Icons.alarm,                size: 80,              ),              onPressed: () {                selectTime(context);              },            ),            SizedBox(              height: 60,            ),            Text('$_time', style: TextStyle(fontSize: 40)),          ],        ),      ),     );  }}
Dart
import 'package:flutter/material.dart';  // Main function which starts the appvoid main() {  runApp(MyApp());}  class MyApp extends StatelessWidget {      // This widget is the root of your application.  @override  Widget build(BuildContext context) {    return MaterialApp(      title: 'Flutter Demo',      theme: ThemeData(                  // This is the theme of your application        primarySwatch: Colors.green,      ),      home: MyHomePage(title: 'GeeksForGeeks'),    );  }}  class MyHomePage extends StatefulWidget {  MyHomePage({Key key, this.title}) : super(key: key);    // This widget is the home page of your application.  final String title;    @override  _MyHomePageState createState() => _MyHomePageState();}  class _MyHomePageState extends State<MyHomePage> {  TimeOfDay _time = TimeOfDay.now();  TimeOfDay picked;    Future<Null> selectTime(BuildContext context) async {    picked = await showTimePicker(      context: context,      initialTime: _time,    );    setState(() {      _time = picked;        print(picked);    });  }    @override  Widget build(BuildContext context) {          // This method is rerun every time setState is called.    return Scaffold(      appBar: AppBar(                  // Here we take the value from the         // MyHomePage object that was created by        // the App.build method, and use it        // to set our appbar title.        title: Text(widget.title),      ),      body: Center(                  // Center is a layout widget. It takes        // a single child and positions it        // in the middle of the parent.        child: Column(          mainAxisAlignment: MainAxisAlignment.center,          children: [            IconButton(              iconSize: 80,              icon: Icon(                Icons.alarm,                size: 80,              ),              onPressed: () {                selectTime(context);              },            ),            SizedBox(              height: 60,            ),            Text('$_time', style: TextStyle(fontSize: 40)),          ],        ), // Column      ), // Center    ); // Scaffold  }}
Output:
Flutter UI-components
Flutter-widgets
Android
Dart
Flutter
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Android Listview in Java with Example
Retrofit with Kotlin Coroutine in Android
How to Change the Background Color After Clicking the Button in Android?
Listview.builder in Flutter
Flutter - DropDownButton Widget
Flutter - Asset Image
Flutter - Custom Bottom Navigation Bar
Splash Screen in Flutter