【问题标题】:Flutter Provider is returning null in initState()Flutter Provider 在 initState() 中返回 null
【发布时间】: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 方法中工作的原因。
  • 好的我明白了,但需要在构建方法之外使用它

标签: flutter flutter-provider


【解决方案1】:

initState 内的直接 context 不能用于 Provider 的所有内容和专业。因此,作为解决方案,请改用didChangeDependencies,例如:

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    dropdownmenuoptions = Provider.of<List<DropdownMenuItem<category.List>>>(
        context,
        listen: false);
    dropdownMenuItem = dropdownmenuoptions.first;
    dropDownValue = dropdownMenuItem.value.name;
  }

如果你真的需要在 initState 中使用它,你可以在 addPostFrameCallback 中使用它

@override
void initState(){
   ...
   SchedulerBinding.instance.addPostFrameCallback((_) {
     dropdownmenuoptions =  Provider.of<List<DropdownMenuItem<category.List>>>(
        context,
        listen: false);
     dropdownMenuItem = dropdownmenuoptions.first;
     dropDownValue = dropdownMenuItem.value.name;
}
});

【讨论】:

猜你喜欢
  • 2020-11-29
  • 1970-01-01
  • 2020-12-11
  • 2021-06-07
  • 2021-02-15
  • 2013-04-18
  • 2020-08-23
  • 2021-09-28
  • 2020-11-10
相关资源
最近更新 更多