How To Use Widget Parameters In State Objects

Corey Gardner
2 min readFeb 20, 2021

--

I am building an app to schedule appointments to a boat detailing service. I created a class called Boat which stores the boats name, length and location. Boat objects are passed into various widgets as a parameter of boat. The initial final cost of a service will vary based on the length of the boat. I decided to store the cost in state because it will change depending on the various options a user selects.

I ran into a problem when trying to set the initial cost in proportion to the boat length that is being passed down to the StatefulWidget:

Class Example extends StatefulWidget {
final Boat boat;
//initialization etc. omitted for brevity
}class _ExampleState extends State<Example> {
double cost = widget.boat.length * 16.0;
//Only Static members can not be accessed in initializers
//.......
}

Upon trying out the code above an error appears saying that static members can’t be accessed in initializers. Naturally I tried to change final to static and got another error which I understand as to say that we can’t use static members for Widget parameters.

I almost had a panic attack I didn’t know what to do ! I thought that I would have to rethink the entire UI.

Luckily I discovered the initState method. According to the Flutter API initState overriding (manually using initState) is used to:

Override this method to perform initialization that depends on the location at which this object was inserted into the tree (i.e., context) or on the widget used to configure this object (i.e., widget).

The case we are dealing with is that of the latter, our state is dependent on the parameter being passed into the Widget.

Class Example extends StatefulWidget {
final Boat boat;
//initialization etc. omitted for brevity
}class _ExampleState extends State<Example> {
// Initialize Variable
double cost;
//And then use initState
@override
void initState(){
cost = widget.boat.length * 16.0; //no Error
super.initState();
}
//.......
}

In the example above I first initialize my state object cost. Next I override initState to manually set this object in proportion to a widget parameter, in this case it is the length of the boat.

Such an easy fix, thanks initState !

Learn Flutter and Ruby here: https://www.youtube.com/channel/UCfd8...

My podcast ; ) https://anchor.fm/coreys-corner

--

--

No responses yet