[英]Flutter, riverpod StateProvider not uploading ui
我正在使用顫振的 Riverpod,並且正在關注提供者。 但是當我更改提供者的值時,構建方法不會被調用。
調用時不會再次調用 build 方法:
ref.read(customObjectProvider.notifier).state.name
這是完整的代碼
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});
}
這里 StateProvider 正在使用MyCustomObject
,這意味着每個狀態都將是一個MyCustomObject
。
此行更新單個變量(名稱),而不是狀態
ref.read(customObjectProvider.notifier).state.name = 'Reuven';
您可以像這樣更新狀態
final MyCustomObject oldObj = ref.read(customObjectProvider);
ref.read(customObjectProvider.notifier).state =
MyCustomObject(name: "newName"); // better will be using copyWith constructor
僅更新單個變量不會刷新,您需要更新狀態以強制刷新
更方便的是使用update
onPressed: () {
ref
.read(customObjectProvider.notifier)
.update((state) => MyCustomObject(name: "newValye"));
},
更多關於state_provider 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.