Flutter 颤振提供程序在initState()中返回null

Flutter 颤振提供程序在initState()中返回null,flutter,flutter-provider,Flutter,Flutter Provider,我从firebase获得DropdownMenuItem列表,其中stream使用provider,如果我在构建中使用provider,它不会返回null,但在initstate中效果很好,即使我将侦听值设置为false,也会返回null 代码如下: List<DropdownMenuItem<category.List>> dropdownmenuoptions; DropdownMenuItem<category.List> dropdownMenuIte

我从firebase获得DropdownMenuItem列表,其中stream使用provider,如果我在构建中使用provider,它不会返回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();
  }

initState
内部的直接
上下文
不能用于
提供者
的所有内容和专业。因此,作为一种解决方案,请使用
didChangeDependencies
,例如:

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

从何处获取在initiate state中使用的上下文?我不是从需要有效上下文才能从提供者获取值的地方获取。在构建方法中有上下文。这就是为什么它在构建方法内部工作。好的,我知道了,但需要在构建方法外部使用它。注释不用于扩展讨论;这段对话已经结束。
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    dropdownmenuoptions = Provider.of<List<DropdownMenuItem<category.List>>>(
        context,
        listen: false);
    dropdownMenuItem = dropdownmenuoptions.first;
    dropDownValue = dropdownMenuItem.value.name;
  }
@override
void initState(){
   ...
   SchedulerBinding.instance.addPostFrameCallback((_) {
     dropdownmenuoptions =  Provider.of<List<DropdownMenuItem<category.List>>>(
        context,
        listen: false);
     dropdownMenuItem = dropdownmenuoptions.first;
     dropDownValue = dropdownMenuItem.value.name;
}
});