状态更新时,消费者小部件不会重建 UI

时间:2021-06-03 20:57:39

标签: flutter dart state-management riverpod

我正在使用 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', Instance of 'Example', Instance of 'Example', Instance of 'Example']

0 个答案:

没有答案