简体   繁体   English

Flutter 肘初始化状态

[英]Flutter Cubit InitState

I am at the begin of my Cubit learning and i tried to create a "Liter-Tracker" with sharedPrefs.我正处于 Cubit 学习的开始阶段,我尝试使用 sharedPrefs 创建一个“Liter-Tracker”。 Everything works but not the init state. I have to press a Button first because I initialize the drinkValue with 0. I tried to return an Int with the value from shared prefs but this dont work:( May you help me?一切正常,但 init state 无效。我必须先按一个按钮,因为我将 drinkValue 初始化为 0。我试图返回一个 Int,其值来自共享首选项,但这不起作用:(你能帮我吗?

This is my cubit:这是我的手肘:

class DrinkCubit extends Cubit<DrinkState> {
  DrinkCubit() : super(DrinkState(drinkValue: 0));


  Future<void> loadCounter() async {
    final prefs = await SharedPreferences.getInstance();

    state.drinkValue = (prefs.getInt('counter') ?? 0);
  }


  Future<int> loadInitCounter() async {
    final prefs = await SharedPreferences.getInstance();

    return state.drinkValue = (prefs.getInt('counter') ?? 0);
  }

}

and this my cubit state:这是我的手肘 state:

class DrinkState {
  int drinkValue;
  int? amount;

  DrinkState({
    required this.drinkValue,

});

}

I also tried something like this in my MainPage, how i usually init my state with setState:我也在我的 MainPage 中尝试过类似的东西,我通常如何使用 setState 初始化我的 state:

  @override
  void initState() {
    super.initState();
    BlocProvider.of<DrinkCubit>(context).loadCounter();
  }

Context is not accessible in initstate, try using didChangeDependencies life cycle method Flutter get context in initState method initstate 中无法访问上下文,尝试使用 didChangeDependencies 生命周期方法Flutter 在 initState 方法中获取上下文

Firstly, I strongly advise you to avoid the StatefulWidget when you use BLoC, but it doesn't mean you can't use it at all.首先,我强烈建议大家在使用BLoC时尽量避免使用StatefulWidget,但并不代表完全不能使用。 Just be careful because setState() can rebuild BlocProvider inside the stateful widget.请小心,因为setState()可以在有状态小部件内重建 BlocProvider。

As for the initialization process, I suggest you use this approach on the BlocProvider.至于初始化过程,我建议你在BlocProvider上使用这种方式。

class DrinkScreen extends StatelessWidget {
  const DrinkScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => DrinkCubit()..loadCounter(), // Or call other initialization method
      child: DrinkView(),
    );
  }
}

This approach works really well if you reuse this screen multiple times, for example, you redirect to DrinkScreen every time you want to fill data and you dispose of the screen afterward ( Navigate.pop() , etc).如果您多次重复使用此屏幕,这种方法非常有效,例如,每次您想要填充数据时都重定向到DrinkScreen ,然后处理屏幕( Navigate.pop()等)。 This way you can automatically initialize the cubit every time you redirect into this screen, you don't need to use StatefulWidget to init the cubit.这样你就可以在每次重定向到这个屏幕时自动初始化 cubit,你不需要使用 StatefulWidget 来初始化 cubit。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM