对于Flutter中BLoC架构的几个实例代码

06/22/2022 08:49 上午 posted in  Flutter

flutter_bloc 使用将从下图的三个维度说明

MultiBlocProvider的使用


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

  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(providers: [
      BlocProvider<HomeBloc>(
        create: (context) => HomeBloc(),
      ),
      BlocProvider<HomeTreatmentCubit>(
        create: (context) => HomeTreatmentCubit(),
      ),
      BlocProvider<HomeOralInspectionCubit>(
        create: (context) => HomeOralInspectionCubit(),
      ),
      BlocProvider<HomeSmileSolutionCubit>(
        create: (context) => HomeSmileSolutionCubit(),
      ),
    ], child: const HomePage());
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
  @override
  void initState() {
    super.initState();
  }

  // _onRefresh 下拉刷新回调
  Future _onRefresh() async {
    Log.d("HomePage execu refresh");
    //HomeBloc homeBloc = BlocProvider.of<HomeBloc>(context);
    //结束刷新
    return Future.value(true);
  }

  @override
  Widget build(BuildContext context) {
    ScrollController scrollController = ScrollController();

    EdgeInsets paddings = MediaQuery.of(context).padding;
    return Scaffold(
      appBar: AppBar(
        backgroundColor: ColorT.appBarBackground,
        leading: Container(),
        title: const Text(
          "首页",
          style: TextStyle(
              fontSize: 18,
              color: ColorT.appBarTitle,
              fontWeight: FontWeight.bold),
        ),
        elevation: 0,
      ),
      body: SafeArea(
        top: false,
        bottom: true,
        left: true,
        right: false,
        child: Container(
          color: ColorT.primaryBackground,
          margin: const EdgeInsets.fromLTRB(0, 0, 0, 0),
          padding: EdgeInsets.fromLTRB(10, 10, 10, paddings.bottom),
          child: RefreshIndicator(
            onRefresh: _onRefresh,
            displacement: 40,
            child: ListView(
              controller: scrollController,
              padding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
              shrinkWrap: true,
              children: const <Widget>[
                HomeTreatmentWidget(),
                HomeOralInspectionWidget(),
                HomeSmileSolutionWidget()
              ],
            ),
          ),
        ),
      ),
    );
  }
}