Gorgon Cyber
 · Cyber Security Start-up

How to use Local state within Custom Widgets and Custom Actions

Several people have been asking about this and have stated that using Local state in Custom Actions and Custom Widgets does not work.

However, that is not entirely true. I have managed to make it work just fine (with a few quirks, but I'll get to that).

First up I have a simple local state variable named test:

I then have a very simple custom action that looks like this:

Notice how the editor complains about FFAppState? We are just going to ignore it. Check errors will also complain - again - we are just going to ignore it.

I also have a custom widget that uses local state. The code looks like this:


Now, the problem with this code is that it also does not compile or preview. We could again just ignore it, but for the sake of having something visible in the editor, I use this little trick:

Now my widget will at least show something in the editor after I compile it. When I then change back to using the real FFAppState, the widget in the editor will just display the last preview that worked (which is actually pretty neat).

So I restore back to the FFAppState line and just click Save

At this stage I'm stuck with these two:

But - I'm just going to pretend they aren't there. They are "Fake News", so to speak.

So let's test it all out. I created a new app with a simple home page:


It has this widget tree:



The Text field is getting its text from the local state:


I then set some actions. The action for the image is first:


So, when I click on the image, both the text field and the custom widget should display the word "Testing".

Next up is the Custom Action. I add two On Tap actions to the Text Widget:







So, when I click the text field, a snack bar should open at the bottom of the screen and show the value of my local state field - ie. "Testing".

Side note: Make sure you set the background color for the snack bar and also the font color. If you leave them unassigned, nothing will show.

So, now just hit "Run >". Our app comes up:

If I click on the image, I get this change:

And if I click on the Text Widget, this shows up at the bottom:

And that is all folks. Local state in both Custom Widgets and Custom Actions.

You could argue that maybe the FF team should fix the incorrect error messages - and I'm sure they will in due course. But at least for now, it should not be stopping your work.

Happy fluttering!!

4
20 replies