Education
Software Development Executive - II
Last updated on Sep 4, 2024
Last updated on Dec 1, 2023
Flutter is a beautiful open-source UI software development kit that allows developers to create visually appealing mobile, desktop, and web applications. In this versatile environment, managing state is a key facet, and Flutter offers several methods to handle it. But today, we’ll focus on one method, the Flutter State Notifier.
One cannot underscore the importance of state management in Flutter. In simple terms, it involves managing the information maintained by an application during its lifecycle. The 'state' is this information, stored in memory and manipulated with user interactions or network responses. However, managing these states can be challenging, especially in larger applications. This is where the Flutter state notifier fits perfectly into your widget tree.
So, let's deeply dive into the Flutter State Notifier, exploring its advantages, usage, and more.
State Notifier is a simple yet potent package for state management in Flutter. The Flutter State Notifier is built to provide an accessible and structured method of managing an immutable state. It differs from other providers in Flutter as it separates the state from the class ("class counter" in this case) that manages it.
We must create a new class extending the StateNotifier class to use the Flutter state notifier. For instance, let's look at a simple counter-example. We'll make a 'CounterNotifier', a class that extends 'StateNotifier'. The initial state of the counter is set as zero. Each time we call the increment function, it modifies the state.
With this, our business logic is isolated, and we can focus on UI updates using consumer widgets.
1class CounterNotifier extends StateNotifier<CounterState> { 2 CounterNotifier() : super(CounterState(counterValue: 0)); 3 4 void increment() { 5 state = CounterState(counterValue: state.counterValue + 1); 6 } 7}
Important to note here is that the state is always an immutable object. The state can never be modified directly. This helps us maintain precision and transparency in our code.
Now, let's dive deeper into the primary constituents of the Flutter state notifier: widget tree, class counter, consumer widget, and business logic.
Imagine a widget tree as your smartphone application’s blueprint. Each widget is a crucial part of the app's structure. Changes in the app state might necessitate rebuilding significant portions of the widget tree. And this is where the state management techniques enter the picture. Efficient use of the Flutter state notifier minimizes the areas of the tree to be rebuilt, thereby ensuring optimal app performance.
Let's consider the simple counter-example to explain the class counter. This class defines the logic, "how the count is incremented." The class counter ensures that the state change happens per our business logic. With the ChangeNotifier class, we can encapsulate our state and define mutating methods.
1class SimpleCounter extends ChangeNotifier { 2 int _count = 0; 3 4 int get count => _count; 5 6 void increment() { 7 _count++; 8 notifyListeners(); 9 } 10}
A consumer widget listens to a provider and re-builds whenever the provider’s data changes. In our counter-example, we would use the Consumer<CounterNotifier>
widget to listen for changes in the counter-state.
In layman's terms, business logic envisions how your application functions—the rules that govern the backend processing of your business' data. Your own business rules and workflows shape these methods. The better the business logic encapsulation, the cleaner the UI code.
With Flutter State Notifier, we can implement state management best practices to organize our business logic and state in a distinct space away from the widget tree.
Now that we have a fair understanding of state notifier and its components, we'll discuss how to implement Flutter notifier provider in application development with a simple counter example.
To kickstart, add the Flutter package and the state_notifier package to your pubspec.yaml file:
1dependencies: 2 state_notifier: ^1.0.0 3 provider: ^version
We start by defining the CounterState as follows:
1class CounterState { 2 final int count; 3 CounterState({required this.count}); 4}
Next, we define a CounterNotifier class that extends StateNotifier with an initial state. Here, we define an action increment() that updates the state:
1class CounterNotifier extends StateNotifier<CounterState> { 2 CounterNotifier() : super(CounterState(count: 0)); 3 4 void increment() { 5 state = CounterState(count: state.count + 1); 6 } 7}
The provider package, in combination with Flutter notifier, helps in accessing the CounterNotifier from the widget tree, as follows:
1Provider((_) => CounterNotifier());
We now build a widget to invoke the increment() method and display the current counter value:
1class CounterPage extends StatelessWidget { 2 @override 3 Widget build(BuildContext context) { 4 return Scaffold( 5 appBar: AppBar(title: Text('Counter Example Using Flutter State Notifier'),), 6 body: Center( 7 child: Column( 8 children: [ 9 Text( 10 context.select((CounterNotifier counterNotifier) => 11 counterNotifier.state.count.toString()), 12 style: TextStyle(fontSize: 40), 13 ), 14 RaisedButton( 15 onPressed: () => 16 context.read<CounterNotifier>().increment(), 17 child: Text('Increment'), 18 ), 19 ], 20 ), 21 ), 22 ); 23 } 24}
And there you go. With this, you've managed your app's state using the Flutter state notifier.
Why should we use the Flutter notifier provider when other state management solutions like Provider, Redux, or BLoC are available? Well, every solution certainly has its benefits, but there are a few reasons why the Flutter state notifier stands out:
It's all about finding the best method for your needs and style. But for many, the Flutter notifier provider has proven invaluable for maintaining a clean and organized codebase.
To wrap up, the Flutter State Notifier is a powerhouse regarding state management in Flutter. It offers a clean and organized way to manage states with a reduced amount of boilerplate code, adding to the readability and maintainability of your Flutter codebase.
While this blog post laid out the benefits and usage of Flutter State Notifier, it's essential to evaluate the needs of your project and your preference for coding styles. As the adage goes, "the right tool for the right job", Flutter provides you with plenty of state management solutions, with the State Notifier being a robust and efficient one.
I hope this post serves as a guided tour into the world of Flutter notifier. So, go forth, experiment with it, try to create your custom classes or widgets, and explore the vast potential it holds. The sky's the limit!
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.