Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Format Time of Day from time picker

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)
like image 706
theSimm Avatar asked May 08 '19 08:05

theSimm


People also ask

How do you convert 12 hours to 24 hours in Flutter?

Convert it to 24 hours format If we set alwaysUse24HourFormat to true, it might convert to 24 hours format but we need to clone the default setting and then change the value in somewhere.

How do you get AM PM from TimePicker in Flutter?

just use format() method to get AM,PM what you required.


1 Answers

This will correctly format TimeOfDay for you:

final localizations = MaterialLocalizations.of(context);
final formattedTimeOfDay = localizations.formatTimeOfDay(timeOfDay);
like image 80
bwhite Avatar answered Nov 15 '22 19:11

bwhite