dependOnInheritedElement() was called before initstate() in flutter

后端 未结 1 1916
难免孤独
难免孤独 2021-01-13 09:44

I am currently having an issue while fetching a Provider\' value ininitstate`.

I want to set a default value in dropdown in an Appbar and other parts i

相关标签:
1条回答
  • 2021-01-13 10:36

    I also mentioned in my previous answer that Provider.of(context) is supposed to be used inside the widget tree, and anything that is outside of the build() method, is not in the widget tree. But if you still want to use it, then you need to set the listen parameter to false.

    Like so:

    @override
      void initState() {
        Provider.of<ButtonData>(context, listen: false).selectedButton = Provider.of<ButtonData>(context, listen: false).buttons.first;
        super.initState();
      }
    

    But as you mentioned in your question, you don't want to use initState to set the default value. In every programming language, when you declare a variable with a value, that value becomes it's initial / default value, and you can change it later.

    Instead of using initState, you can edit the following in your ButtonData class.

    //Remove this.
    List<Button> get buttons => _buttons;
      Button _selectedButton;
      Button get selectedButton => _selectedButton;
    
    //Instead, Use this.
    List<Button> get buttons => _buttons;
    Button _selectedButton = _buttons.first;
    Button get selectedButton => _selectedButton;
    
    //This will declare the `selectedButton` variable with a default value.
    //Happy coding! :)
    
    0 讨论(0)
提交回复
热议问题