A time picker is a popup window that allows to select a time.
We can use showTimePicker() function to display a time picker. If the user confirms the dialog then function returns a Future that completes to the selected time. If the user cancels the dialog, null is returned.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: MyApp()));
class MyApp extends StatefulWidget {
  const MyApp({super.key});
  @override
  State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
  TimeOfDay _time = TimeOfDay.now();
  _showTimePicker(BuildContext context) async {
    final TimeOfDay? picked = await showTimePicker(
      context: context,
      initialTime: _time,
    );
    if (picked != null && picked != _time) {
      setState(() {
        _time = picked;
      });
    }
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: const Text('Time picker')),
        body: Center(
            child: ElevatedButton(
          child: const Text('Open'),
          onPressed: () => _showTimePicker(context),
        )));
  }
} 
             
                         
                         
                        
Leave a Comment
Cancel reply