skip to Main Content

I’m currently developing Android/iOS apps using flutter_riverpod.
And I’m trying to redraw the UI using StateNotifierProvider.
However, although the state should have been updated, only the UI is not updated.

My StateNotifierProvider code

Here, user information is managed by StateNotifierProvider.

final myProvider =
    StateNotifierProvider<MyProvider, MyData>(
        (ref) => MyProvider(MyData()));

class MyData {
  bool myBool = false;
  String? text;
}

class MyProvider extends StateNotifier<MyData> {
  MyProvider(super.state);

  Future<void> update(){
    state.myBool = true;
  }
}

My ref.read code

This is called when the user presses a particular button.

void onTapButton() {
  ref.read(myProvider).update();
}

My UI code

Here I’m showing a simple UI that shows what’s going on with myBool in MyData.
But display false after pushed button onTapButton().

class Main extends ConsumerWidget {
  @override
  build (context, ref) {

    bool b = ref.watch(myProvider).myBool;

    return Scaffold(
      body: Center(
        child: Text(b.toString()), // always false...
      ),
    );
  }
}

When I redraw the screen using hot reload, the UI will be updated to show true.

2

Answers


  1. Chosen as BEST ANSWER

    I solved with freezed package.


  2. StateNotifier need use the setter method state = MyData() to notifier to listeners

    class MyProvider extends StateNotifier<MyData> {
      MyProvider(super.state);
    
      Future<void> update(){
        final previousState = state;
        state = MyData()..text = previousState.text..myBool=true;
      }
    }
    

    Consider implementing copyWith function for your MyData so you don’t need to do final previousState = state; like my example. And the state (MyData) should be immutable.

    See StateNotifierProvider for more information.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search