【问题标题】:I can't consume a Bloc with Get it in Flutter我不能在 Flutter 中使用 Get it 来消费 Bloc
【发布时间】:2022-01-02 06:45:45
【问题描述】:

我正在尝试使用 GetIt 消费一个集团,但出现此错误:

错误:在此 BlocBuilder Widget 上方找不到正确的提供程序

发生这种情况是因为您使用了不包含提供程序的 BuildContext 你的选择。有几种常见的情况:

GetIt 不应该在没有 Provider 的情况下使用 bloc 吗?我该如何解决?

下面是我的代码:

void main() {
  setupServiceLocator();
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home:  MyHomePage(),
    );
  }
}
class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  late GetUserProfileBloc bloc;

  @override
  void initState() {
    super.initState();

    bloc = sl.get<GetUserProfileBloc>();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(

        title: Text(widget.title),
      ),
      body: BlocBuilder<GetUserProfileBloc, GetUserProfileState>(builder: (context, state) {
        if (state is GetUserProfileInitialState) {
          return const Center(child: Text("initial"));
        } else if (state is GetUserProfileLoadingState) {
          return const Center(child: CircularProgressIndicator());
        } else if (state is GetUserProfileSuccessState) {
          return Center(child: Text(state.userProfile.toString()),);
        } else {
          return const Center(child: Text("sssssss"),);
        }
      }),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          bloc.add(GetUserProfileEvent());
        },
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

【问题讨论】:

    标签: flutter bloc flutter-provider


    【解决方案1】:

    我从不使用这种方法。试试这个,它有效。如果你很难获得上下文,那么将你的脚手架绑定到 final scaffoldKey = GlobalKey();将其放入脚手架参数 Scaffold(key: scaffoldKey, ); 使用scaffoldKey,你可以得到你的currentContext!

    late PostBloc bloc;
    
    @override
    Widget build(BuildContext context) {
      bloc = BlocProvider.of<PostBloc>(context);
    }
    

    或者使用这个技巧

    @Override    
    Widget build(BuildContext context) {
            return MultiBlocProvider(
              providers: [
                BlocProvider(
                    create: (context) => SomeServiceBloc()..add(CheckLocationOnEnd())),
        )], child .... );
    

    【讨论】:

      猜你喜欢
      • 2019-08-22
      • 2014-10-02
      • 2023-01-23
      • 2021-09-20
      • 2023-01-05
      • 2021-10-26
      • 2019-11-20
      • 2021-10-30
      • 2020-04-11
      相关资源
      最近更新 更多