簡體   English   中英

我如何使 bloc 可用於所有 flutter 應用程序頁面

[英]how can i make bloc available for all flutter app pages

我正在使用 bloc 來管理我的應用程序 state,我想為我的所有應用程序頁面提供 bloc,因此我已將其插入到小部件樹的頂部,以便我可以從小部件樹中的任何位置使用它,我已將其用作以下

1- 主頁

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MyAppState();
  }}

  class MyAppState extends State<MyApp>{

  @override
  Widget build(BuildContext context) {
    return BlocProvider<MyBloc>(
      create: (BuildContext context) {
        return MyBloc();
      },
      child: MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: secondPage()),
    );
  }
}

2-秒頁:

 class SecondPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return SecondPage State();
  }
}

class SecondPage State extends State<SecondPage > {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('secondPage')),

        body: BlocBuilder<CityBloc, CityState>(
          builder: (BuildContext context, CityState state) {            
             .......  
          },));}}

但 flutter 顯示錯誤

BlocProvider.of() called with a context that does not contain a Bloc of type MyBloc

這是應用程序小部件樹的屏幕截圖小部件樹屏幕截圖

,什么是錯誤,我想為所有小部件提供 mybloc

注意:如果我在同一頁面中寫入 MainPage class 和 secondPage class,應用程序運行正常,但是當我將它們分開時出現錯誤

我對解決方案感到震驚,問題僅在導入中,我已更換

import '../blocs/blocs.dart';

import 'package: loony_trips / blocs / blocs.dart';

一切都是固定的,即使這兩個句子應該是一樣的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM