Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Happy coding!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading