Search code examples
flutterriverpod

Why is my Flutter Riverpod counter not updating on UI?


Main Flutter Counter

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'data/providers.dart';

void main() {
  runApp(
    // For widgets to be able to read providers, we need to wrap the entire
    // application in a "ProviderScope" widget.
    // This is where the state of our providers will be stored.
    ProviderScope(
      child: MyApp(),
    ),
  );
}

class MyApp extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    var men = ref.watch(populationController).men.toString();

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Example')),
        body: Center(
            child: Column(
          children: [
            Text("Amount of men is $men"),
            IconButton(
                onPressed: () {
                  ref.read(populationController.notifier).increaseMen();
                },
                icon: const Icon(Icons.plus_one))
          ],
        )),
      ),
    );
  }
}

File where I define riverpod class

import 'package:flutter_riverpod/flutter_riverpod.dart';

class PopulationTracker {
  int women = 0;
  int men = 0;
}

class PopulationNotifier extends StateNotifier<PopulationTracker> {
  PopulationNotifier() : super(PopulationTracker());

  void increaseMen() {
    state.men += 1;
  }

  void increaseWomen() {
    state.women += 1;
  }

  void minusWomen() {
    state.women -= 1;
  }

  void minusMen() {
    state.men -= 1;
  }
}

final populationController =
    StateNotifierProvider<PopulationNotifier, PopulationTracker>(
        (ref) => PopulationNotifier());



I was trying to update the state of my population tracker using riverpod and flutter. I am pretty new to this and cannot figure out why the counter on UI does not update I can see the value update if I print the value of state to console.

I was expecting the counter to update to +1 on UI but it does not.

Why does the counter not update on UI?


Solution

  • The state object is not changing identity. Just mutating. Mutating is not enough to emit a new event to listeners. You need to treat state as readonly and use operations like copyWith to make it work.

    Also, you should move away from StateNotifier and start using Notifier. If you had been using Notifier, I could also advise you to merely add ref.notifyListeners() for your mutate methods, and get it to work that way.

    In summary, please stop using ChangeNotifier, StateNotifier, and StateProvider. They are supported only for legacy purposes.