Hi Everyone, It took me a bit to figure out how to update the state of a custom widget. In other words, how to redraw it when a value changes. I assumed that I needed to trigger a call to setState(). Turns out that it's easier than that, but maybe not obvious. The magic is that the Widget State's build() method gets called whenever there is a change to Local State. So, all we need to do is refer to Local State variables in our Widget State's build method, and poof! It works. Here is a simple example to illustrate this. It is a simple Random Number Generator. When the user clicks a button, a new random number is shown. Step 1. Create a Local State Variable to Hold the Random ValueIn this case, my Local State variable is randomNum, and it is an Integer.[Screen Shot 2022-11-22 at 5.35.35 PM.png] Step 2. Create a Custom Widget That Displays the Random Value The key here is to leverage FFAppState(), which refers to our Local State. randomNum is the Local State variable created in step 1. In this case, I've called toString() because randomNum is an integer.
“class RandomValue extends StatefulWidget {
const RandomValue({
Key? key,
this.width,
this.height,
}) : super(key: key);
final double? width;
final double? height;
@override
_RandomValueState createState() => _RandomValueState();
}
class _RandomValueState extends State {
@override
Widget build(BuildContext context) {
return Text(FFAppState().randomNum.toString(),textAlign: TextAlign.center, style: TextStyle(fontSize: 20));
}
}”
Step 3. Create the User Interface The UI is simple -- just our custom widget and a button that can be clicked to show a new random number.[Screen Shot 2022-11-22 at 5.56.44 PM.png] Step 4. Add an Action to the ButtonThe last step is to add an action to the button which updates our Local State variable, randomNum. We use the "Update Local State" action to update randomNum to a random integer. [Screen Shot 2022-11-22 at 6.18.04 PM.png]And, Here's the result...[Screen Recording 2022-11-22 at 6.21.04 PM.gif]