I am currently having an issue while fetching a Provider\' value in
initstate`.
I want to set a default value in dropdown in an Appbar and other parts i
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! :)