web-dev-qa-db-ja.com

タイムピッカーからの日のフラッターフォーマットの時間

私のFlutterアプリのタイムピッカーから選択した時間をフォーマットしようとしています。私は理由がわからないが、これはそれがそうであるべきであるよりも難しいことを証明している。私が達成しようとしている最終結果は、Minuetsまたは午後5:00。ユーザーがタイムピッカーウィジェットから時間を選択した後、これはボックスコンテナに表示されます。私はselcted時間をフォーマットする 'timeformater()'と呼ばれるメソッドがありますが、私はエラー'flutter:type' timeofday 'が' widget 'iのsubtypeではありません。コードを実行してください。 TimeOfday()をフォーマットするためのFlutterにはより簡単な方法/メソッドがありますか?

私のコード:

      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,
        ),
      ],
    );
  }
}
 _

エラーメッセージ:

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)
 _
5
theSimm

これはあなたのためにTimeOfDayを正しくフォーマットします。

final MaterialLocalizations localizations = MaterialLocalizations.of(context);
final String formattedTimeOfDay = localizations.formatTimeOfDay(timeOfDay);
 _
4
bwhite

これは、私が日付の時間とTimeOfdawayを使用して、それらの値をFlutterプラットフォームで同じ時間内に分離するのです。

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;
  });
} }
 _
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
  });}
 _
0
Johny Saini

日付ピッカーから日付を選ぶため

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,
   ),
   ),
   ),
   ),
 _

日付を選ぶための方法

 _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;
  });
}}
 _
0
BC TUBE

DatePicker.ShowTimePickerを使用できます

    DatePicker.showTimePicker(context,  
            showTitleActions: true,  
                onChanged: (date) {  
                 print('change $date');  
            }, onConfirm: (date) {  
                 print('confirm $date');  
            }, currentTime: DateTime.now(), locale: LocaleType.pt);
 _
0
linhadiretalipe