How to Add Time Picker in Flutter

Sometimes, we need specific time input from the users. Time pickers are used in such situations. In this blog post, let’s see how to add a time picker in Flutter.

I already have a blog post that shows how to add a date picker in flutter. Flutter has an inbuilt function named showTimePicker to display the time picker. It returns the selected date too.

showTimePicker(
    initialTime: TimeOfDay.now(),
    context: context);

Following is the complete Flutter timepicker example. It displays a time picker when the user taps on the TextField widget. For that purpose, we use onTap attribute of TextField. We make the readOnly attribute true so that the user can’t modify the text using the keyboard.

import 'package:flutter/material.dart';
void main() => runApp(App());

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Time Picker example',
      home: TimePicker(),
    );
  }
}

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

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

class _TimePickerState extends State<TimePicker> {
  final timeController = TextEditingController();

  @override
  void dispose() {
    // Clean up the controller when the widget is removed
    timeController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body:Center(child: TextField(
         readOnly: true,
         controller: timeController,
         decoration: InputDecoration(
            hintText: 'Pick your Time'
  ),
         onTap: () async {
        var time =  await showTimePicker(
              initialTime: TimeOfDay.now(),
              context: context,);
        timeController.text = time.format(context);      
       },)),);
  }
}

Following is the output of Flutter time picker example with textfield.

I hope this flutter tutorial will help you. Stay tuned for more flutter tutorials.

Leave a Comment

Your email address will not be published. Required fields are marked *