【问题标题】:TimeOfDay' is not a subtype of type 'DateTime?TimeOfDay' 不是“DateTime”类型的子类型?
【发布时间】:2021-12-08 18:48:49
【问题描述】:

这是我用来显示时间选择器的代码

var selectedTime;

void initState() {
super.initState();
selectedDate = DateTime.now();
selectedTime = TimeOfDay(hour: 23, minute: 23);



}


_selectTime(BuildContext context) async {
final TimeOfDay? picked = await showTimePicker(
  context: context,
  initialTime: selectedTime,
);
if(picked != null && picked != selectedTime)
  setState(() {
    selectedTime = picked;
  });

}

这是我用来将数据发送到另一个屏幕的代码

SizedBox(width: 120,
          child: ElevatedButton(
              child: Text('Continue'),
              onPressed: (){
                widget.book.selectedDate  = selectedDate;
                widget.book.selectedTime= selectedTime;
                Navigator.push(context, MaterialPageRoute(builder: (context)=> NewBookFinishView(book: widget.book)),
                );
              },
          ),
        )

但是当我按下继续发送日期和时间的值时,我得到一个错误 TimeOfDay' 不是“DateTime”类型的子类型?请帮忙。

【问题讨论】:

  • 你的意思是widget.book.selectedTime = selectedTime;
  • 是的,对不起,我改了,但错误还是一样

标签: flutter dart


【解决方案1】:

您尝试在您的onPressed 中分配两次您的widget.book.selectedDate(您可能使用了错误的变量):

widget.book.selectedDate = selectedDate; // 1st assign with a DateTime
widget.book.selectedDate = selectedTime; // 2nd assign with a TimeOfDay

即使您的selectedDatedynamic,第一个分配是DateTime,您也无法分配selectedTime 的值,因为它是TimeOfDay 类型。

【讨论】:

  • widget.book.selectedTime= selectedTime;我把它改成这个,但错误还是一样。
  • 那么这意味着在某些时候你给你的变量widget.book.selectedTime分配了错误的类型。我想你已经在你的班级var selectedTime 中声明了它。而不是使用类型推断,您应该像这样清楚地定义变量的类型:TimeOfDay selectedTime
猜你喜欢
  • 1970-01-01
  • 2021-09-18
  • 1970-01-01
  • 2020-02-11
  • 2022-11-28
  • 2021-11-20
  • 1970-01-01
  • 2018-06-08
  • 2020-06-26
相关资源
最近更新 更多