问题描述
我正在使用 Flutter riverpod(State Notifier Provider)进行状态管理。当我更新状态时,消费者小部件不会自行重建,因为即使我的状态正在更新,UI 也不会更新。我无法调试原因。
Pubspec.yaml
_
Riverpod StateNotifier 提供程序
Flutter_riverpod: ^0.14.0+3
供应商
final dataListModelProvider=StateNotifierProvider((ref)=>ExampleProvider ([]));
Riverpod 消费者小部件
class ExampleProvider extends StateNotifier<List<Example>>{
ExampleProvider (List<Example> state):super(state ?? []);
void createExample(Map exampleData) async{
try{
var response= await ExampleDao().createExampleData(exampleData); // API request - working fine( All the data is coming back from API as expected)
print(" ===== CREATED EXAMPLE TYPE===========");
Example example=response;
List<Example> listExampleData= [...state,example];
print("========== INITIAL STATE =============Count = ${state.length}");
print(state);
state=listExampleData;
print("========== UPDATED STATE =============Count = ${state.length}");
print(state);
}
}catch(error,stackTrace){
print(error);
print(stackTrace);
}
}
}
更新状态的按钮
Consumer(builder: (context,watch,child){
print("STEP-1");
dynamic value=context.read(dataListModelProvider.notifier).state;
print("STEP-2");
print(value);
return FutureBuilder(
future: watch(dataFetchDataProvider),builder: (context,snapshot){
if(snapshot.connectionState==ConnectionState.done){
print("######## SNAPSHOT VALUE ############");
print(snapshot.data);
return mainUI(size,_width,_height,isNull(value) ||
value.length==0?snapshot.data:value);
}
else{
return Center(
child: CircularProgressIndicator(backgroundColor:
SolidColor.colorWhite),);
}
});
}),
基于初始状态构建时的控制台输出(启动屏幕时)
RaisedButton(
onpressed:context.read(dataListModelProvider.notifier).createExample(inputListData),child: Text('CLICK HERE'),)
调用create函数后(更新状态时)
STEP-1
STEP-2
[]
######## SNAPSHOT VALUE ############
[Instance of 'Example',Instance of 'Example',Instance of
'Example',Instance of 'Example']
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)