【问题标题】:Where should I initialize the blocs in flutter_bloc我应该在哪里初始化flutter_bloc中的块
【发布时间】:2021-01-29 02:16:47
【问题描述】:

我正在使用 Flutter_bloc 包来处理颤振中的 bloc 模式,但我想知道在 main 函数中使用 MultiBlocProvider 并像这样添加我所有的 bloc 是否是一个好习惯:

  void main()async{
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(Mafqood());
}

class Mafqood extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
       return MultiBlocProvider(
         providers : [
           BlocProvider<AuthBloc>(
           create:  (context) => AuthBloc(AuthInitialState(), AuthRepository()),
          ),

           BlocProvider<LoginBloc>(
             create: (context) => LoginBloc(LoginInitialState(), AuthRepository()),
           ),

           BlocProvider<ProfileBloc>(
             create:  (context) => ProfileBloc(ProfileInitialState(), AuthRepository()),
           ),

         ],
         child: MaterialApp(

或者最好在我需要的地方添加集团?为什么? 提前致谢。

【问题讨论】:

    标签: flutter dart flutter-bloc


    【解决方案1】:

    您应该像以前一样在 main 函数中使用 MultiBlocProvider。这是最佳实践。这就是提供者的目标。

    编辑:

    现在我意识到还有另一个答案here

    【讨论】:

      【解决方案2】:

      MultiBlocProvider 的主要用途是在您必须定义哪个 bloc 依赖于另一个 bloc 之前,在应用程序的不同位置使用 bloc 对象。

      如果你有一个应用,每个屏幕都使用自己的块,那么你就不需要MultiBlocProvider,因为你可以在屏幕的构建函数中创建块

      class ParentScreen extends StatelessWidget {
        const ParentScreen ({Key? key, this.data}) : super(key: key);
        final data;
      
        @override
        Widget build(BuildContext context) {
          return BlocProvider<MyBloc>(
              create: (_) => MyBloc()),
              child: MyScreenBody());
        }
      }
      Class MyScreenBody extends StatefulWidget {
        const MyScreenBody({Key? key}) : super(key: key);
      
        @override
        _MyScreenBodyState createState() => _MyScreenBodyState();
      }
      
      class _MyScreenBodyState  extends State<MyScreenBody> {
        @override
      
        void initState() {
          super.initState();
        }
      
        @override
        Widget build(BuildContext context) {
            return Scaffold(
                  body: BlocBuilder<MyBloc, MyState>(
                    builder: (context, state) {
                  return //... your code
                  }
                )
              );
        }
      

      【讨论】:

        猜你喜欢
        • 2016-03-26
        • 2011-02-12
        • 2011-11-04
        • 2019-04-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-09
        相关资源
        最近更新 更多