Home > Mobile >  Flutter, riverpod StateProvider not uploading ui
Flutter, riverpod StateProvider not uploading ui

Time:07-08

I am using flutter riverpod, and I am watching a provider. But when I change the value of the provider, the build method is not being called.

The build method is not called again when I call :

    ref.read(customObjectProvider.notifier).state.name

Here is the full code

final customObjectProvider = StateProvider((ref) => MyCustomObject());

class CustomClassProviderScreen extends ConsumerWidget {
  const CustomClassProviderScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final stateObject = ref.watch(customObjectProvider);

    return Scaffold(
      appBar: AppBar(
        title: Text('Custom Object Provider'),
      ),
      body: Column(
        children: [
          ElevatedButton(
              onPressed: () {
                ref.read(customObjectProvider.notifier).state.name = 'Reuven';
              },
              child: Text('Button 1: Name')),
          ElevatedButton(
              onPressed: () {
                ref.read(customObjectProvider.notifier).state.id = '338755093';
              },
              child: Text('Button 2: ID')),
          Text(stateObject.name ?? ''),
          Text(stateObject.id ?? ''),
        ],
      ),
    );
  }
}

class MyCustomObject {
  String? name;
  String? id;

  MyCustomObject({this.name, this.id});
}

CodePudding user response:

Here StateProvider is using MyCustomObject, means every state will a MyCustomObject.

This line update the single variable(name), not the state

ref.read(customObjectProvider.notifier).state.name = 'Reuven';

You can update the state like

final MyCustomObject oldObj = ref.read(customObjectProvider);
ref.read(customObjectProvider.notifier).state =
    MyCustomObject(name: "newName"); // better will be using copyWith constructor

Just updating single variable won't refresh, You need to update the state to force a refresh

More handy is by using update

onPressed: () {
  ref
      .read(customObjectProvider.notifier)
      .update((state) => MyCustomObject(name: "newValye"));
},

More about state_provider.

  • Related