State Management in Flutter
Flutter
State Management

State Management in Flutter

Diluk Udayakantha

Diluk Udayakantha

Flutter Developer

April 02, 2025•8 min read

State management is one of the most important concepts to understand when building Flutter applications. Choosing the right strategy can make your app easier to develop, debug, and maintain. This article explores various state management solutions in Flutter and helps you decide which one to use for different scenarios.

Understanding State in Flutter

Before diving into different state management solutions, let's understand what state actually means in a Flutter application:

  • Ephemeral (Local) State: UI state that is contained within a single widget (like scroll position, form inputs)
  • App State: State that is shared across multiple widgets or the entire app (user data, authentication status, app configuration)

The complexity of your state management should match the complexity of your app's state.

1. setState - The Simplest Solution

Flutter's built-in setState() method is the simplest way to manage local state:

class CounterWidget extends StatefulWidget {
  @override
  _CounterWidgetState createState() => _CounterWidgetState();
}

class _CounterWidgetState extends State {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text('Count: $_counter'),
        ElevatedButton(
          onPressed: _incrementCounter,
          child: Text('Increment'),
        ),
      ],
    );
  }
}
          

When to use setState:

  • For simple UI state that's confined to a single widget
  • When you're learning Flutter for the first time
  • For small-scale apps with minimal state requirements

2. InheritedWidget and InheritedModel

InheritedWidget is the foundation of state management in Flutter. Many popular packages are built on top of this concept:

class CounterProvider extends InheritedWidget {
  final int counter;
  final Function increment;
  
  CounterProvider({
    Key? key,
    required Widget child,
    required this.counter,
    required this.increment,
  }) : super(key: key, child: child);
  
  static CounterProvider of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType()!;
  }
  
  @override
  bool updateShouldNotify(CounterProvider oldWidget) {
    return oldWidget.counter != counter;
  }
}
          

When to use InheritedWidget:

  • When you want to understand state management fundamentals
  • For creating custom state management solutions
  • When you need fine-grained control over widget rebuilds

3. Provider

Provider is a wrapper around InheritedWidget to make it easier to use and test:

// Define your model
class CounterModel with ChangeNotifier {
  int _count = 0;
  int get count => _count;

  void increment() {
    _count++;
    notifyListeners();
  }
}

// Set up the provider
void main() {
  runApp(
    ChangeNotifierProvider(
      create: (context) => CounterModel(),
      child: MyApp(),
    ),
  );
}

// Use the provider in your widgets
class CounterDisplay extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer(
      builder: (context, counter, child) => Text(
        'Count: ${counter.count}',
      ),
    );
  }
}

class CounterIncrement extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () => context.read().increment(),
      child: Text('Increment'),
    );
  }
}
          

When to use Provider:

  • For small to medium-sized applications
  • When you need a simple, lightweight solution
  • As an introduction to reactive programming concepts

4. Riverpod

Riverpod is an improved version of Provider that solves some of its limitations:

// Define your providers
final counterProvider = StateNotifierProvider((ref) {
  return CounterNotifier();
});

class CounterNotifier extends StateNotifier {
  CounterNotifier() : super(0);
  
  void increment() => state++;
}

// Use the provider
class CounterWidget extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final count = ref.watch(counterProvider);
    
    return Column(
      children: [
        Text('Count: $count'),
        ElevatedButton(
          onPressed: () => ref.read(counterProvider.notifier).increment(),
          child: Text('Increment'),
        ),
      ],
    );
  }
}
          

When to use Riverpod:

  • When you need compile-time safety for your providers
  • For better testability and maintainability
  • When you've outgrown Provider

5. Bloc Pattern

BLoC (Business Logic Component) separates presentation from business logic using streams:

// Define your events
abstract class CounterEvent {}
class IncrementEvent extends CounterEvent {}

// Define your bloc
class CounterBloc extends Bloc {
  CounterBloc() : super(0) {
    on((event, emit) {
      emit(state + 1);
    });
  }
}

// Use your bloc
class CounterPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => CounterBloc(),
      child: CounterView(),
    );
  }
}

class CounterView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        BlocBuilder(
          builder: (context, count) {
            return Text('Count: $count');
          },
        ),
        ElevatedButton(
          onPressed: () => 
            context.read().add(IncrementEvent()),
          child: Text('Increment'),
        ),
      ],
    );
  }
}
          

When to use BLoC:

  • For larger applications with complex business logic
  • When working with reactive streams is preferred
  • For teams with clear separation of concerns

6. GetX

GetX offers a lightweight solution with minimal boilerplate:

// Define your controller
class CounterController extends GetxController {
  var count = 0.obs;
  
  void increment() => count++;
}

// Use your controller
class CounterWidget extends StatelessWidget {
  final CounterController controller = Get.put(CounterController());
  
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Obx(() => Text('Count: ${controller.count}')),
        ElevatedButton(
          onPressed: controller.increment,
          child: Text('Increment'),
        ),
      ],
    );
  }
}
          

When to use GetX:

  • When you need a quick development cycle
  • If you prefer minimal boilerplate code
  • For projects that need integrated navigation and dependency injection

7. MobX

MobX is a battle-tested library that provides a simple way of managing state:

// Define your store
class CounterStore = _CounterStore with _$CounterStore;

abstract class _CounterStore with Store {
  @observable
  int count = 0;
  
  @action
  void increment() {
    count++;
  }
}

// Use your store
class CounterWidget extends StatelessWidget {
  final CounterStore store = CounterStore();
  
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Observer(
          builder: (_) => Text('Count: ${store.count}'),
        ),
        ElevatedButton(
          onPressed: store.increment,
          child: Text('Increment'),
        ),
      ],
    );
  }
}
          

When to use MobX:

  • For teams familiar with MobX from web development
  • When you need transparent reactive programming
  • For applications with complex interdependent state

8. Redux

Redux provides a predictable state container with a unidirectional data flow:

// Define actions
enum Actions { Increment }

// Define reducer
int counterReducer(int state, dynamic action) {
  if (action == Actions.Increment) {
    return state + 1;
  }
  return state;
}

// Set up store
final store = Store(counterReducer, initialState: 0);

// Use in widgets
class CounterWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StoreConnector(
      converter: (store) => store.state,
      builder: (context, count) {
        return Column(
          children: [
            Text('Count: $count'),
            ElevatedButton(
              onPressed: () => 
                StoreProvider.of(context)
                  .dispatch(Actions.Increment),
              child: Text('Increment'),
            ),
          ],
        );
      },
    );
  }
}
          

When to use Redux:

  • For large applications with complex state transitions
  • When you need time-travel debugging
  • For teams already familiar with Redux from web development

Choosing the Right Solution

There's no one-size-fits-all answer to state management in Flutter. Here's a quick decision guide:

Solution Best For
setState Small widgets with local state
Provider Small to medium apps, getting started with state management
Riverpod Medium-sized apps, improved Provider experience
Bloc Large apps with complex business logic
GetX Rapid development with minimal boilerplate
MobX Reactive applications with complex state dependencies
Redux Large applications with predictable state changes

Conclusion

The best state management solution depends on your app's requirements, team size, and personal preference. Start simple with setState or Provider, and only adopt more complex solutions as your needs grow.

Remember that you can use different state management solutions for different parts of your app. For example, you might use setState for UI state and Riverpod for application state.

Regardless of which solution you choose, the key is to be consistent, maintain clean architecture, and ensure your state flows in a predictable manner throughout your application.