【问题标题】:Error: The argument type 'Future<Null>' can't be assigned to the parameter type 'TimeOfDay'错误:无法将参数类型“Future<Null>”分配给参数类型“TimeOfDay”
【发布时间】:2019-10-17 02:39:45
【问题描述】:

我正在尝试将时间选择器添加到我的颤振应用程序中。我正在尝试将时间格式化为 12 小时制。但问题是当我尝试传递我的时间变量来格式化时,它给了我这样的错误。

错误:无法将参数类型“Future”分配给参数类型“TimeOfDay”。

到目前为止,我就是这样做的。

DateTime _currentDate = new DateTime.now();
  TimeOfDay _currentTime = new TimeOfDay.now();



  Future <Null> selectedTime;

  String timeText = 'Set A Time';
  @override
  Widget build(BuildContext context) {

    /// Time Picker

      MaterialLocalizations localizations = MaterialLocalizations.of(context);
      String formattedTime = localizations.formatTimeOfDay(selectedTime,  <--Here i am getting error
          alwaysUse24HourFormat: false);

      if (formattedTime != null) {
        setState(() {
          timeText = formattedTime;
        });
      }

时间选择器小部件

时间选择器(

                  icon: Icons.access_time,
                  selectedTime: '$timeText',
                  onPress: () {


                    selectedTime = showTimePicker(
                      context: context,
                      initialTime: _currentTime,
                    );
                  },
                ),

有什么办法可以解决这个问题。

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您的 selectedTime 必须是 TimeOfDay 而不是 Future&lt;Null&gt;

    【讨论】:

      【解决方案2】:

      selectedTime 更改为TimeOfDay 类型,将onPress 更改为async 函数和await showTimePicker,以便您获得Future 的值而不是Future

      TimeOfDay selectedTime;
      
      TimePicker(
        icon: Icons.access_time,
        selectedTime: '$timeText',
        onPress: () async {
          selectedTime = await showTimePicker(
            context: context,
            initialTime: _currentTime,
          );
        },
      ),
      

      【讨论】:

      • 我现在收到此错误The getter 'hourOfPeriod' was called on null. Receiver: null Tried calling: hourOfPeriod 这是什么意思?
      • 这意味着在您的代码中某处您正在对一个为空的变量调用hourOfPeriod。你还没有分享你的那部分代码,所以我不能给出任何准确的指示。
      猜你喜欢
      • 2020-11-20
      • 2020-10-22
      • 2021-06-04
      • 2021-12-27
      • 2020-01-05
      • 2021-07-09
      • 2021-08-22
      • 2021-11-03
      • 2022-08-14
      相关资源
      最近更新 更多