How to use TimePicker in Flutter

Key takeaways:

  • Flutter enables developers to create fast mobile, web, and desktop applications with a single codebase.

  • The TimePicker widget allows users to select specific times for various applications like alarms and event scheduling.

  • Date and time pickers are essential for user-friendly mobile applications, ensuring standardized data entry.

  • A simple TimePicker can be implemented by creating a Flutter project and defining a TimeOfDay object.

  • The showTimePicker function displays the TimePicker dialog for users to select a time.

  • Updating the selected time is done using setState to reflect changes in the UI.

  • Running the Flutter application will allow users to interact with the TimePicker and select their desired time.

  • The implementation of TimePicker can be customized to meet specific application needs.

Flutter is a powerful toolkit created by Google to build fast mobile, web, and desktop applications using just one codebase. It offers an easy-to-use and flexible development environment, making it a popular choice for developers to create beautiful and responsive user interfaces across multiple platforms.

TimePicker

TimePicker is a widget that allows users to select a specific time from a dialog or a panel. It’s commonly used in applications where users need to input a time, such as setting an alarm, scheduling an event, or choosing a time for a reminder.

The showTimePicker function is Flutter’s standard method for time selection, opening a dialog to let users pick a time. In the following code widget, the TimePickerWidget class customizes this function for a modular, reusable UI.

Importance of TimePicker

It is impossible to develop a user-friendly mobile application without using a date, time, or date and time picker. These components not only allow the user to enter their required date and time instantly but also help ensure the data is entered in a standardized format, leading to fewer discrepancies and errors. They are highly used in booking applications, event applications, and task management applications.

Creating a TimePicker

Let’s follow the steps below to create an TimePicker in the Flutter application:

1- Create a Flutter project

Let’s start by creating a new Flutter project. For this, open the terminal and execute the following commands:

flutter create timepicker
cd timepicker

2- Create the user interface

Let’s create a simple TimePicker inside the TimePickerWidget class in main.dart file. We have created a simple TimeOfDay object named _selectedTime which is initialized with the current time of the day and then displayed on the screen. This is given in the line below:

TimeOfDay _selectedTime = TimeOfDay.now();

The showTimePicker function

Inside the TimePickerWidget, we create a Future<void> function that contains showTimePicker function to display the time picker widget, and it allows the user to select a specific time. This selected time will be stored in the TimeOfDay variable named picked. Initially, the picked time will be equal to the _selectedTime variable. This is implemented in the following code:

final TimeOfDay? picked = await showTimePicker(
context: context,
initialTime: _selectedTime,
);

Whenever the new time is selected by the user, the _selectedTime variable is updated by the picked time. This is shown in the following code:

if (picked != null && picked != _selectedTime) {
setState(() {
_selectedTime = picked;
});
}

Now, we will create a Column widget that contains the selected time displayed and ElevatedButton, when pressed, calls the _selectTime functions and opens the widget, which allows the user to select the desired time. This is implemented in the following code:

Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Selected Time: ${_selectedTime.format(context)}',
style: TextStyle(fontSize: 20),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () => _selectTime(context),
child: const Text('Select Time'),
),
],
);

3- Complete implementation

Following is the complete code of the Flutter application with the implementation of a TimePicker:

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- The INTERNET permission is required for development. Specifically,
         the Flutter tool needs it to communicate with the running application
         to allow setting breakpoints, to provide hot reload, etc.
    -->
    <uses-permission android:name="android.permission.INTERNET"/>
</manifest>
Implementation of complete application

Note: You can find your application running at the given link once you run the code widget above.

The showTimePicker function includes several properties to customize the TimePicker’s appearance and behavior:

Property

Description

context

The BuildContext in which the dialog is displayed. Required for accessing the current state of the widget tree.

initialTime

The initial time displayed when the dialog is opened, as a TimeOfDay object. Required for setting the starting time in the picker.

builder

A function that wraps the dialog widget to allow for custom designs or additional inherited widgets (e.g., Localizations.override, Directionality, or MediaQuery).

barrierDismissible

If true, allows the dialog to be dismissed by tapping outside the dialog; defaults to true.

useRootNavigator

If true, the dialog will use the root navigator; if false, it uses the navigator of the current context. Defaults to true.

initialEntryMode

Defines the initial mode for entering time, either TimePickerEntryMode.dial (default) or TimePickerEntryMode.input (text input)

cancelText

Custom text for the cancel button. If not specified, defaults to "Cancel."

confirmText

Custom text for the confirm button. If not specified, it defaults to "OK."

helpText

Custom help text displayed at the top of the time picker. If not specified, defaults to "Select time."

errorInvalidText

Custom error text shown when an invalid time is entered.

hourLabelText

Custom label for the hour field in text input mode.

minuteLabelText

Custom label for the minute field in text input mode.

routeSettings

Settings for the route used to navigate to the dialog, like name and arguments

onEntryModeChanged

A callback triggered when the entry mode is changed (e.g., switching between dial and input mode).

anchorPoint

Determines the origin point for displaying the dialog on a split screen. By default, it depends on the Directionality widget if not specified.

orientation

Sets the orientation (portrait or landscape) for the dialog display. By default, it adapts based on the device's screen size.

Conclusion

Using the TimePicker widget in Flutter enhances the user experience by simplifying the process of selecting time. This straightforward implementation can be expanded and customized according to the needs of your application, making it a valuable addition to any Flutter project.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How to pick a date and time in Flutter?

To pick a date and time in Flutter, use showDatePicker for the date and showTimePicker for the time:

// Date picker
Future<DateTime?> selectedDate = showDatePicker(
  context: context,
  initialDate: DateTime.now(),
  firstDate: DateTime(2000),
  lastDate: DateTime(2100),
);

// Time picker
Future<TimeOfDay?> selectedTime = showTimePicker(
  context: context,
  initialTime: TimeOfDay.now(),
);

How to show time in Flutter

To show the current time in Flutter, you can use DateTime.now() to get the current time and format it with the intl package if needed.

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class TimeDisplay extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    String formattedTime = DateFormat('hh:mm:ss a').format(DateTime.now()); // Format the time
    return Scaffold(
      appBar: AppBar(title: Text("Current Time")),
      body: Center(
        child: Text(
          formattedTime, 
          style: TextStyle(fontSize: 48),
        ),
      ),
    );
  }
}

void main() => runApp(MaterialApp(home: TimeDisplay()));

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved