StateX
Tags: flutter
Published: 2024-02-12 00:55:48

---
title: StateX
published: true
date: 2022-08-25 16:12:15 UTC
tags: flutter
canonical_url: https://andrious.medium.com/statex-60bc9957bf20
---

_The long-awaited extension of the State class_

When I first began learning Flutter back in 2018, I kept getting two particular warning messages. It was obvious I was doing something wrong and not taking full advantage of Flutter’s declarative approach to programming. These messages are conveyed in the two screenshots below:

![](https://cdn-images-1.medium.com/max/1024/0*Nvdc4kgquC-flUpq.png)
<figcaption>‘@immutable’ warning</figcaption>


![](https://cdn-images-1.medium.com/max/1024/0*X6bF0sDobP1gS3My.png)
<figcaption>‘setState’ warning</figcaption>

### The Warnings: ‘@immutable’ and ‘setState’

StatelessWidgets and StatefulWidgets are to contain unchanging (immutable) instance fields or properties — not doing so impedes Flutter’s functionality and degrades its overall performance. As for not calling the State class’ **setState**() function directly but through a subclass, that’s just good practice. It’s currently a ‘protected’ function — you’re to implement a subclass to call such a function.

When working with Flutter, you always need reliable access to a particular State object to call its **setState**() function (or at least a StatefulElement’s **markNeedsBuild**() function). Doing so ‘rebuilds’ that portion of the screen involving that State object and reflects the changes made to the state object.

> _“ There is no imperative changing of the UI itself (like_ _widget.setText)—you change the state, and the UI rebuilds from scratch.”_

> _— flutter.dev_ [_Start thinking declaratively_](https://flutter.dev/docs/development/data-and-backend/state-mgmt/declarative)

Now all your ‘mutable’ code could go into the Dart file containing your State subclass. At first glance, that’s a good idea. Again, you always want ready access to the State object and its **setState**() function. However, that can make for a rather large and unmanageable Dart file. No, more often than not, placing such code in separate Dart files would be a better solution.

And so, I wrote the package [state\_extended](https://pub.dev/packages/state_extended) with its class, StateX. Now, this is not to be confused with [GetX](https://pub.dev/packages/get). StateX involves extending the functions and features of the Sate class. As such, X stands for ‘extension,’ The StateX class contains 24 new functions compared to Flutter’s original State class. However, GetX and StateX do have their similarities. In particular, both involve ‘controllers’ that generally contain the ‘business logic’ involved in any given app. GetX has its GetxController class while StateX has its StateXController class. The difference here is that the StateX controllers can do anything its associated StateX object can do and more. This article will now introduce this.

### I Like Screenshots. Tap Caption For Gists.

As always, I prefer using screenshots in my articles over gists to show concepts rather than just show code. I find them easier to work with frankly. However, you can click or tap on their captions to see the code in a gist or in Github. Tap or click on the screenshots themselves to zoom in on them for a closer look. With that, you ironically will find it best to read this article about mobile development on your computer rather than on your phone.

### No Moving Pictures, No Social Media

There will be _gif_ files in this article demonstrating aspects of the topic at hand. However, it’s said viewing such _gif_ files is not possible when reading this article on platforms like Instagram or Facebook. They may come out as static pictures or simply blank placeholders. Please, be aware of this and maybe read this article on medium.com or on their own app.

Let’s begin.

![](https://cdn-images-1.medium.com/max/1024/1*MOiPveeMav88yJsticSd7w.png)
<figcaption><a href="https://dev.to/andrious">Other Stories by Greg Perry</a></figcaption>


So again, when I began working with Flutter back in 2018, it was clear I needed a separate class representing the ‘Business Logic’ of the app but had ready access to the ever-important State object. The [StateX](https://pub.dev/packages/state_extended#statex) class was the result.

“Ephemeral state (sometimes called UI state or local state) is the state you can neatly contain in a single widget.

Other parts of the widget tree seldom need to access this kind of state. In other words, there is no need to use state management techniques (ScopedModel, Redux, etc.) on this kind of state. All you need is a StatefulWidget.”

— flutter.dev [Ephemeral state](https://flutter.dev/docs/development/data-and-backend/state-mgmt/ephemeral-vs-app#ephemeral-state)

I would have written the last sentence a little more explicitly:   
“All you need is a StatefulWidget with its State object retaining state.”

### Show By Example
We’ll use the ol’ startup app created with every new Flutter project to demonstrate the StateX class in action. Here is a gist file for you to download and try yourself: [statex\_counter\_app.dart](https://gist.github.com/Andrious/0ca1dd1b2409f8eb31c3809ed9c0a4b8). Below is a screenshot of this startup app. You can see there have been some changes made. The class, State, has been replaced with the class, StateX, and then that class object takes in a StateXController object named…well, …Controller.

![](https://cdn-images-1.medium.com/max/1024/1*EbDgCOxSa0xzRQr42TOGog.png)
<figcaption><a href="https://gist.github.com/Andrious/0ca1dd1b2409f8eb31c3809ed9c0a4b8#file-statex_counter_app-dart-L1">statex_counter_app.dart</a></figcaption>

As you now know, you should extend the State class to use it, and in this case, you have to extend the StateX class to use it. You’ll be glad you did—because it now includes a controller and much more capability as well as scalability.

In the next screenshot below, you can see highlighted with red arrows that the Controller object is referenced here and there in the State object’s **build**() function. By design, the controller is providing the data and the event handling necessary for the app to function correctly. However, do you see something missing in the screenshot? There’s no **setState**() function call?! It’s in the controller and called in the con. **onPressed**() function.

![](https://cdn-images-1.medium.com/max/1024/1*NxrmnGJuVNo7-WuDSJI_Wg.png)
<figcaption><a href="https://gist.github.com/Andrious/0ca1dd1b2409f8eb31c3809ed9c0a4b8#file-statex_counter_app-dart-L27">statex_counter_app.dart</a></figcaption>

Looking at the screenshot of the controller class below, you’ll find the **setState**() function call. Now, that’s a powerful capability! You’re in a class that can contain all the mutable properties and business logic you want as well as provide state management! It further has access to the State object’s own properties: _widget_, _mounted,_ and _context._ Imagine what you’re controller can do with access to those properties as well.

![](https://cdn-images-1.medium.com/max/1024/1*Wtff5SoNzJdAOCR-Vm8KpA.png)
<figcaption><a href="https://gist.github.com/Andrious/0ca1dd1b2409f8eb31c3809ed9c0a4b8#file-statex_counter_app-dart-L27">statex_counter_app.dart</a></figcaption>

It’s easy enough to see when this link to the State object occurred. It happened when the StateX class was first instantiated. It’s there where the controller object was also instantiated and passed to the State object (see below). With that, the business logic component now has access to a State object and vice versa.

![](https://cdn-images-1.medium.com/max/1024/1*zo5N6A7dVKgn0YM5YKjWSw.png)
<figcaption><a href="">statex_counter_app.dart</a></figcaption>

As an aside, if you don’t want your ‘business logic’ dictating the ‘look and feel’ of your app’s interface, simply remove the **setState** () function call from the controller and return it back to the **build** () function (see below). Let the State object dictate when to call its **setState** () function instead. If you know me, you know I want developers to have options.

![](https://cdn-images-1.medium.com/max/1024/1*_fXoiyPMypJVieP4IR30UA.png)
<figcaption><a href="">statex_counter_app.dart</a></figcaption>

### Control The State

When using this [package](https://pub.dev/packages/state_extended), through the course of an app’s lifecycle, a controller can be registered to any number of StateX objects. A StateXController object works with ‘the last’ State object it’s been assigned to but keeps a reference of any and all past StateX objects it’s worked with previously in the Widget tree. Very powerful.

When a screen closes (i.e. the current StateX object is disposed of), the controller focus points back to the previous StateX it was assigned to. This allows, for example, for one controller to sustain the app’s business logic for the duration of the running app while conveying that logic across any number of screens (i.e. any number of StateX objects).

![](https://cdn-images-1.medium.com/max/253/1*x1qnWzfmhG8Z9WJVNYvL_Q.png)
<figcaption>‘First In, Last Out’ when queuing a controller’s State objects.</figcaption>
As it happens, in turn, a StateX object can have any number of controllers during the app’s lifecycle. Each controller could, for example, be dedicated to a particular responsibility independent of the other controllers or the rest of the app — encouraging more modular development of the software.

![](https://cdn-images-1.medium.com/max/240/1*7vctAgGEittQNOJVitNvaw.png)
<figcaption>One State with many controllers</figcaption>

As a quick example, the screenshot of our simple example app below demonstrates some additional controller objects ‘linked’ to a StateX object.

![](https://cdn-images-1.medium.com/max/1024/1*D57zSapWf99CXX5JRaTwqw.png)
<figcaption><a href="">statex_counter_app.dart</a></figcaption>

### Xtend The State

Let’s finish up this article by simply listing the additional functions and features you gain when you use the StateX class. The first list below contains all functions unique to the StateX class. Most pertain to retrieving a particular controller currently linked to the StateX object. Later articles will demonstrate these functions in detail and note the examples on [Github](https://github.com/AndriousSolutions/state_extended/tree/master/example) and [Pub.dev](https://pub.dev/packages/state_extended#example-code).

> **_add_** _(StateXController? controller)   
> Add a specific StateXController to this State object._

> **_addList_** _(List<StateXController>? list)  
> Add a list of ‘Controllers’ to be associated with this StatX object._

> _StateXController? get_ **_controller_**  
> _Provide the ‘first’ controller added to this State object   
> (allowed multiple controllers)._

> _U?_ **_controllerByType_** _<U extends StateXController>()  
> Retrieve a StateXController by type (allowed multiple controllers)._

> **_onError_** _(FlutterErrorDetails details)   
> Its own Error Handler. The default routine is to dump the error to the console._

### Find Your State

This next list is of functions found only in a StateXController object. Most here retrieve a particular StateX object currently running in the app. You’ll find this an indispensable capability.

> **_addState_** _(StateX? state)  
> Associate this StateXController to a specified StateX object._

> _StateX? get_ **_state_**  
> _This getter returns the ‘current’ StateX object (can have many of them)._

> **_setState_** _(VoidCallback fn)   
> Calls the ‘current’ StateX object’s_ **_setState_** _() function._

> **_stateOf_** _<T extends StatefulWidget>()  
> Retrieve a State object by its StatefulWidget (can have many of them)._

> **_ofState_** _<T extends StateX>()  
> Retrieve a StateX object by type (can contain multiple State objects)._

### Share a Lifecycle Together

Lastly, there are twenty-one event handlers added to the StateX class in the [state\_extended](https://pub.dev/packages/state_extended) package, and when a controller is linked to a StateX object, it too then has access to these event handlers and to events that may be triggered in the app. I suspect Android developers in particular will recognize this as an indispensable capability as well.

### Init for One, Init for All

A screenshot of the StateX class and its **initState** () function below, presents how a StateX object, after running its own **initState** () function, then runs the **initState** () function of each and every controller currently associated with it at the time. You see, each controller may have its own operations or services that need to run before the StateX object can continue. Instead of a large and messy **initState** () function in the one State object — there can be individual controllers running their own **initState** () functions. Very clean. Very modular.

![](https://cdn-images-1.medium.com/max/1024/1*RCxOKzl8CexPQndyNhqbFg.png)
_state_extended.dart_

> **_initState_** _()   
> Called exactly once when the State object is first created._

> **_initAsync_** _()   
> Called exactly once at the app’s startup to initialize any ‘time-consuming’ operations that need to complete for the app can continue._

> **_dispose_** _()   
> When the State object will never build again. Its terminated._

> **_didUpdateWidget_** _(StatefulWidget oldWidget)   
> Override this method to respond when the State object’s accompanying StatefulWidget is destroyed and a new one recreated — a very common occurrence in the life of a typical Flutter app._

> **_didChangeDependencies_** _()  
> When a dependency of this State object changes._

> **_didChangePlatformBrightness_** _()  
> Brightness changed._

> **_didChangeLocale_** _(Locale locale)  
> When the user’s locale has changed._

> **_didChangeMetrics_** _()  
> When the application’s dimensions change. (i.e. when a phone is rotated.)_

> **_reassemble_** _()  
> Called during hot reload. (e.g. reassembled during debugging.)_

> **_didPopRoute_** _()  
> Called when the system tells the app to pop the current route._ **_didPushRoute_** _(String route)  
> Called when the app pushes a new route onto the navigator._

> **_didPushRouteInformation_** _(RouteInformation routeInformation)  
> Called when pushing a new RouteInformation and a restoration state  
> onto the router._

> **_deactivate_** _()  
> When the State object is removed from the Widget tree._

> **_didChangeTextScaleFactor_** _()  
> When the platform’s text scale factor changes._

> **_didHaveMemoryPressure_** _()  
> When the phone is running low on memory._

> **_didChangeAccessibilityFeatures_** _()  
> When the system changes the set of active accessibility features._

> _d_ **_idChangeAppLifecycleState_** _(AppLifecycleState state)  
> Called when the app’s in the background or returns to the foreground.  
> The four following functions use this one to address specific events._

> **_inactiveLifecycleState_** _()  
> The application is in an inactive state and is not receiving user input._

> **_pausedLifecycleState_** _()  
> The application is not currently visible to the user, not responding to  
> user input, and running in the background._

> **_detachedLifecycleState_** _()  
> Either be in the progress of attaching when the engine is first initializing  
> or after the view being destroyed due to a Navigator pop._

> **_resumedLifecycleState_** _()  
> The application is visible and responding to user input._

### StateX Series

You can continue from this intro. to the 4-part series of articles below that even further examines the functions and features of the [state\_extended](https://pub.dev/packages/state_extended) package. Each will detail one of the four example apps that accompany the package when it’s installed.

[![](https://cdn-images-1.medium.com/max/1024/1*8vz7GYtfGDBVCo1ZwCim4g.jpeg)](https://andrious.medium.com/statex-story-1-6368ea7e4fb3)

[![](https://cdn-images-1.medium.com/max/1024/1*F5YnEUevs-5LBim2SpOOfg.jpeg)](https://andrious.medium.com/statex-story-2-aeed86a902b3)

[![](https://cdn-images-1.medium.com/max/1024/1*qdn0QZqFGE6-PaiOwv6EkQ.jpeg)](https://andrious.medium.com/statex-story-3-aab382d47f10)

[![](https://cdn-images-1.medium.com/max/1024/1*9uSCSzs8jCD-WVQ0Kun3aw.jpeg)](https://andrious.medium.com/statex-story-4-b6d25441af0d)

Cheers.