Search code examples
flutterriverpod

ref.watch does not work on value changes to json_annotationed StateProvider


Provider

final userP =
    StateProvider<UserModel>((ref) => UserModel( null));

@JsonSerializable() class UserModel { String? intro;

UserModel(this.intro);

factory UserModel.fromJson(Map<String, dynamic> json) => _$UserModelFromJson(json);

Map<String, dynamic> toJson() => _$UserModelToJson(this); }

Widget

final user = ref.watch(userP);
      Text(user.intro ?? 'innntro null?!'),
      ElevatedButton(
        onPressed: () {
          ref.read(userP.notifier).state.intro = 'change!';
        },
        child: Text('change intro'))
      )

I have this riverpod provider and when I update the value with ElevatedButton, I see that it has been updated with print() value. However, it does not update the widget. It does that when I refresh the app with pressing r on termianl.

Is there a reason why and what am I doing it wrong here?


Solution

  • I tried your example, and when I change onPressed() like this it successfully updated

    ref.read(userP.notifier).update((state) => UserModel('change'));