【发布时间】:2021-04-12 05:35:52
【问题描述】:
如果我在构建中使用提供程序,它不会返回 null 效果很好,但在 initstate 中即使我设置监听值 false 返回 null。
代码如下:
List<DropdownMenuItem<category.List>> dropdownmenuoptions;
DropdownMenuItem<category.List> dropdownMenuItem;
String dropDownValue;
@override
void initState() {
dropdownmenuoptions = Provider.of<List<DropdownMenuItem<category.List>>>(
context,
listen: false);
dropdownMenuItem = dropdownmenuoptions.first;
dropDownValue = dropdownMenuItem.value.name;
super.initState();
}
这是错误信息:
The following NoSuchMethodError was thrown building Builder:
The getter 'first' was called on null.
Receiver: null
Tried calling: first
The relevant error-causing widget was
MaterialApp
lib/main.dart:37
When the exception was thrown, this was the stack
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 _HomeScreenState.initState
package:tobetter/…/home/home_screen.dart:73
#2 StatefulElement._firstBuild
package:flutter/…/widgets/framework.dart:4833
#3 ComponentElement.mount
package:flutter/…/widgets/framework.dart:4649
... Normal element mounting (24 frames)
【问题讨论】:
-
从哪里获取您在启动状态中使用的上下文?
-
我不是从某处得到的
-
您需要一个有效的上下文才能从提供者那里获取价值。您在 build 方法中有上下文。这就是它在 build 方法中工作的原因。
-
好的我明白了,但需要在构建方法之外使用它