getter'bloc'被调用为null

时间:2020-03-25 20:47:18

标签: flutter dart bloc

我编写了一个应用程序以列出所有对象,但是我不知道为什么在运行应用程序后,控制台会向我抛出此类错误:

 The following NoSuchMethodError was thrown building HomePage(dirty, state: _HomePageState#ebfc2):
I/flutter (22800): The getter 'bloc' was called on null.
I/flutter (22800): Receiver: null
I/flutter (22800): Tried calling: bloc

也许以前有人遇到过类似的错误,可以帮助我解决该错误吗?

这是我的代码, 我的body来自HomePage()

中的小部件
body: StreamBuilder<List<Order>>(
          stream: bloc.orders,
          builder: (context, snapshot) {
            if(!snapshot.hasData){
              return Center(child: CircularProgressIndicator());
            }else{
              return ListView.builder(
                itemCount: snapshot.data.length,
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text(snapshot.data[index].title),
                  );
                },
              );
            }
          },

我的OrderBloc.dart

class OrderBloc{
  final _orders = BehaviorSubject<List<Order>>();

  Stream<List<Order>> get orders => _orders.stream;
  Function(List<Order>) get changeOrders => _orders.sink.add;

  dispose(){
    _orders.close();
  }

  Future<void> fetchOrders() async{
    var response = await http.get("http://10.0.2.2:80/order");
    var jsonResponse = convert.jsonDecode(response.body);
    var orderJson = jsonResponse as List;
    List<Order> orders = List<Order>();

    orderJson.forEach((orders) => orders.add(Order.fromJson(orders)));
    changeOrders(orders);
  }
}

和我的OrderProvider.dart

class OrderProvider extends InheritedWidget{
  final OrderBloc bloc;

  OrderProvider({Key key, Widget child})
    :bloc = OrderBloc(),
    super(key:key, child:child);

    bool updateShouldNotify(_) => true;

    static OrderBloc of (BuildContext context){
      // return(context.inheritFromWidgetOfExactType(OrderProvider) as OrderProvider)
      return context.dependOnInheritedWidgetOfExactType<OrderProvider>()
      .bloc;
    }
}

0 个答案:

没有答案