21

I am trying to format the selected time from time-picker in my flutter app. I don't know why but this is proving to be more difficult than it should be. The end result I am trying to achieve is hour:minuets or 5:00pm. This will display in a box container after user has picked the time from the time-picker widget. I have a method called 'timeFormater()' which will format the selcted time but i'm getting the error 'flutter: type 'TimeOfDay' is not a subtype of type 'Widget' when I run my code. Is there an easier way/method in flutter for formatting TimeOfDay()?

My Code:

      import 'package:flutter/material.dart';
    import 'package:flutter/cupertino.dart';
    import 'package:intl/intl.dart';
    import 'package:auto_size_text/auto_size_text.dart';
    import 'dart:io' show Platform;

    class DateTimePicker extends StatefulWidget {
      @override
      _DateTimePickerState createState() => _DateTimePickerState();
    }

    class _DateTimePickerState extends State<DateTimePicker> {
      DateTime _date = new DateTime.now();
      TimeOfDay _time = new TimeOfDay.now();
      Duration initialtimer = new Duration();
      DateTime _datePicked;
      TimeOfDay _timePicked;


      @override
      void initState() {
       // timeController.addListener(_time);

      }

      @override
      Widget build(BuildContext context) {
        return Container(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                // mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  dateContainer(),
                  timeContainer()
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  customDatePicker(context),
                  customTimePicker(context)
                ],
              ),
            ],
          ),
        );
      }
 Widget customTimePicker(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(left: 12.0),
      child: FlatButton(
          child: Text('Time', style: TextStyle(
              color: Colors.white
          ),),
          color: Colors.deepOrange,
          onPressed: () => _selectedTime(context)
      ),
    );
  }
 Future<Null> _selectedTime(BuildContext context) async {
    _timePicked = await showTimePicker(
        context: context,
        initialTime: _time);

    if (_timePicked != null) {
      setState(() {
        _time = _timePicked;
      });
    }
  }
 Widget timeContainer() {
    return Container(
      width: 100,
      height: 100,
      child: Padding(
          padding: const EdgeInsets.only(left: 16.0, top: 16.0,bottom: 16.0),
          child: Container(
            decoration: BoxDecoration(
              border: Border.all(
                width: .5,
                color: Colors.black
              )
            ),
            child: timeFormater(),
          )
      ),
    );
  }

  Widget timeFormater() {
    return Column(
      children: <Widget>[
        SizedBox(
          height: 20.0,
        ),
        _timePicked != null
            ? TimeOfDay(hour: _timePicked.hour, minute: _timePicked.minute)
            : SizedBox(
          width: 0.0,
          height: 0.0,
        ),
      ],
    );
  }
}

Error Message:

flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
flutter: The following assertion was thrown building DateTimePicker(dirty, dependencies: [_InheritedTheme,
flutter: _LocalizationsScope-[GlobalKey#6c45d]], state: _DateTimePickerState#7eeb8):
flutter: type 'TimeOfDay' is not a subtype of type 'Widget'
flutter:
flutter: Either the assertion indicates an error in the framework itself, or we should provide substantially
flutter: more information in this error message to help you determine and fix the underlying cause.
flutter: In either case, please report this assertion by filing a bug on GitHub:
flutter:   https://github.com/flutter/flutter/issues/new?template=BUG.md
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #0      _DateTimePickerState.timeFormater (package:rallie_app/utils/custom_date_timer.dart:176:13)
flutter: #1      _DateTimePickerState.timeContainer (package:rallie_app/utils/custom_date_timer.dart:163:20)
flutter: #2      _DateTimePickerState.build (package:rallie_app/utils/custom_date_timer.dart:37:15)
flutter: #3      StatefulElement.build (package:flutter/src/widgets/framework.dart:3830:27)
flutter: #4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3741:15)
flutter: #5      Element.rebuild (package:flutter/src/widgets/framework.dart:3564:5)
flutter: #6      BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2277:33)
flutter: #7      _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:700:20)
flutter: #8      _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:275:5)
flutter: #9      _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:990:15)
flutter: #10     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:930:9)
flutter: #11     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:842:5)
flutter: #15     _invoke (dart:ui/hooks.dart:209:10)
flutter: #16     _drawFrame (dart:ui/hooks.dart:168:3)
flutter: (elided 3 frames from package dart:async)
theSimm
  • 450
  • 4
  • 9
  • 16
  • `TimeOfDay` is not a `Widget` like `Text`, `Container`, `SizedBox` etc - you have to return a `Widget` from your `timeFormater()` method – pskink May 08 '19 at 08:06
  • Is there a way to format the TimeOfDay to show hour:minutes? Even if i add it to a text widget it still doesn't solve my problem if i can't get it to display properly – theSimm May 09 '19 at 03:26
  • if you want to format `TimeOfDay` use `format()` method – pskink May 09 '19 at 04:34
  • Can you add more clarification such as a code example that works. I have tried using the TimeOfDayFormat.H_colon_mn method but it doesn't format the time that was selected from the time picker – theSimm May 09 '19 at 05:03

9 Answers9

37

This will correctly format TimeOfDay for you:

final localizations = MaterialLocalizations.of(context);
final formattedTimeOfDay = localizations.formatTimeOfDay(timeOfDay);
bwhite
  • 2,643
  • 1
  • 18
  • 8
  • 1
    This seems to be the correct way to get the string output. It should be an accepted answer. – Purvik Rana Jan 16 '20 at 14:38
  • 2
    It is a nice solution, but being dependent on the context, is not suitable for usage where it is not available. – funder7 Dec 29 '20 at 14:36
  • @funder7 If you use StateManagement like GetX, you can simply use Get.context inside a string return type method wrapping the code above. – Akradhi Dec 09 '21 at 07:59
  • 1
    @Akradhi I don't know GetX sorry.. What I meant was that if the solution depends on `context`, then it will not be usable where `context` is not available. It's just something to take in consideration, but not necessarily a blocker! I would say that having the context available is a must if you need to format `TimeOfDay` properly. But honestly I'm away from Flutter since ~6 months, someone else will surely be more prepared on the subject than me :-) – funder7 Dec 13 '21 at 18:23
  • @funder7 You can check out the framework. I provided the link below. https://pub.dev/packages/get It's really easy to implement and we don't much have to worry about the context much after this. – Akradhi Jan 18 '22 at 09:29
  • It gave me "09:00 AM" or "0700 PM" which is completely useless to send to the database per json – MwBakker Oct 11 '22 at 18:53
6

String time = _timePicked.format(context);

  • 1
    Very straightforward solution! +1. Just wondering how to specifiy the display format (12h AM/PM vs 24h) with this solution compared to the one from @bwhite. – Fabrice Jul 05 '20 at 12:16
  • @Fabrice Try this. This is specifically for your case: import 'package:flutter/material.dart'; String formatTime( {BuildContext context, TimeOfDay timeOfDay, bool alwaysUse24HourFormat = false}) { final localizations = MaterialLocalizations.of(context); final formattedTimeOfDay = localizations.formatTimeOfDay(timeOfDay, alwaysUse24HourFormat: alwaysUse24HourFormat); return formattedTimeOfDay; } – Akradhi Dec 09 '21 at 07:57
  • This creating conflicts with Getx and whole app is re-rendering again – Syed Daniyal Ali Jun 09 '22 at 23:51
3

This is how i use Date Time and TimeOfDay to get their values separate in the same time on flutter platform.

static DateTime _eventdDate = DateTime.now();

static var now =
  TimeOfDay.fromDateTime(DateTime.parse(_eventdDate.toString()));



 String _eventTime = now.toString().substring(10, 15);



Future _pickTime() async {
TimeOfDay timepick = await showTimePicker(
    context: context, initialTime: new TimeOfDay.now());

if (timepick != null) {
  setState(() {
    _eventTime = timepick.toString().substring(10, 15);
  });
} }

Future _pickDate() async {

DateTime datepick = await showDatePicker(
    context: context,
    initialDate: new DateTime.now(),
    firstDate: new DateTime.now().add(Duration(days: -365)),
    lastDate: new DateTime.now().add(Duration(days: 365)));

if (datepick != null) {
  setState(() {
    _eventdDate = datepick;
  });
} }
1

Text_timePicked.format(context);

you can convert the value

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 01 '22 at 05:21
0

You can use DatePicker.showTimePicker

    DatePicker.showTimePicker(context,  
            showTitleActions: true,  
                onChanged: (date) {  
                 print('change $date');  
            }, onConfirm: (date) {  
                 print('confirm $date');  
            }, currentTime: DateTime.now(), locale: LocaleType.pt);
linhadiretalipe
  • 907
  • 7
  • 8
0
  String timeValue ='Select Time';
  TimeOfDay selectedTime =TimeOfDay.now();

  Future<Null> _selectTime(BuildContext context) async {
  final TimeOfDay picked_s = await showTimePicker(
    context: context,
    initialTime: selectedTime, builder: (BuildContext context, Widget 
  child) {
       return MediaQuery(
         data: 
       MediaQuery.of(context).copyWith(alwaysUse24HourFormat:false),
        child: child,
      );});

if (picked_s != null && picked_s != selectedTime )
  setState(() {
    selectedTime = picked_s;
    timeValue = picked_s.format(context);   //time convert into string formate
  });}
Johny Saini
  • 879
  • 1
  • 5
  • 6
0

To pick Date from Date Picker.

DateTime pickedDate;

@override
void initState() {
super.initState();
pickedDate = DateTime.now();
currentTime = "${pickedDate}";
time = TimeOfDay.now();
}

Container(
   width: width/2.3,
   child: InkWell(
   onTap: () {
   _pickDate();
   },
   child: IgnorePointer(
   child: AppTextField(
   text: "${pickedDate.day}/${pickedDate.month}/${pickedDate.year}",
   suffixIcon: Icon(Icons.calendar_today),
   onTextChnage: null,
   ),
   ),
   ),
   ),

Method to to Pick Date

 _pickDate() async{
DateTime date = await showDatePicker(
    context: context,
    initialDate: pickedDate,
    firstDate: DateTime(DateTime.now().year-10),
    lastDate: DateTime(DateTime.now().year+10)
);
debugPrint("${pickedDate} ${time}");
//debugPrint(date as String);
if(date != null){
  setState(() {
    pickedDate = date;
  });
}}
BC TUBE
  • 664
  • 5
  • 15
0

Here is the best way to remove TimeOfDay from showTimePicker

    if (pickedTime != null && pickedTime != _timeOfDay) {
  setState(() {
    _timeOfDay = pickedTime;
    String timeOfDay = pickedTime.format(context);
    print(timeOfDay);
  });
}
-1

This question is not about TimeOfDay - you just try to use value as a widget. In your code change this

 _timePicked != null
        ? TimeOfDay(hour: _timePicked.hour, minute: _timePicked.minute)

to

_timePicked != null
        ? Text(TimeOfDay(hour: _timePicked.hour, minute: _timePicked.minute)
            .toString())

and it will work.

awaik
  • 10,143
  • 2
  • 44
  • 50