How to format time from time picker in flutter

I’m new to flutter. In my app I have a button which onPressed shows a timepicker. I want to set the title of the button to the time selected by user in this format: 2:30 PM. To do that I need to format the time. I’m using the intl package but can’t seem to figure out how to use it to format the time. Here’s the code:

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

class ShowTimePickerWidget extends StatefulWidget {
  const ShowTimePickerWidget({super.key});

  @override
  State<ShowTimePickerWidget> createState() => _ShowTimePickerWidgetState();
}

class _ShowTimePickerWidgetState extends State<ShowTimePickerWidget> {
  TimeOfDay? selectedTime;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        const Icon(Icons.access_time),
        Expanded(
          child: TextButton(
            onPressed: () async {
              TimeOfDay time = TimeOfDay.now();
              final pickedTime = await showTimePicker(
                context: context,
                initialTime: time,
              );
              setState(() {
                selectedTime = pickedTime;
              });
            },
            child: Text(
              (selectedTime == null)
                  ? 'Time to start your day'
                  : //set the formatted time string here,
            ),
          ),
        ),
      ],
    );
  }
}

intl version: 0.18.1

>Solution :

I think this is what you need, if not, please let me know and I will provide more support.

Happy coding!

Leave a Reply