访问继承的小部件时,在null上调用了Getter

时间:2018-12-22 22:36:20

标签: dart flutter

尝试在flutter中使用继承的小部件时遇到此错误。

The getter 'serviceListBloc' was called on null.
I/flutter ( 3525): Receiver: null
I/flutter ( 3525): Tried calling: serviceListBloc

我的代码

@override
Widget build(BuildContext context) {

final abc = ServiceProvider.of(context).serviceListBloc;

 return MaterialApp(
  title: 'Learning Json Parse',
  home: Scaffold(
    appBar: AppBar(
      title: Text('Learning Json Parse'),
    ),
    body: ServiceProvider(
      serviceListBloc: ServiceListBloc(),
      child: StreamBuilder(
      stream: bloc.allServices,
      builder: (BuildContext context, AsyncSnapshot<ServiceList> snapshot) {
        if (snapshot.hasError) return Text('Error: ${snapshot.error}');
        switch (snapshot.connectionState) {
          case ConnectionState.none:
            return Text('Select lot');
          case ConnectionState.waiting:
            return Text('Awaiting bids...');
          case ConnectionState.active:
          case ConnectionState.done:
             List services = snapshot.data.services;
            return ListView.builder(
              itemCount: services.length,
              itemBuilder: (context, index) {
                return Center(
                  child: Text(snapshot.data.services[index].category),
                );
              },
            );
        }
        return null; // unreachable
      },
    ),
    ),
    floatingActionButton: FloatingActionButton(
      child: Icon(Icons.add),
      onPressed: () => bloc.updateServices(),
    ),
  ),
);

}  }

我的继承小部件是

class ServiceProvider extends InheritedWidget{
   final ServiceListBloc serviceListBloc;

  ServiceProvider({Key key, Widget child, this.serviceListBloc}) 
   : super(key:key, child:child);

  @override
  bool updateShouldNotify(InheritedWidget oldWidget) => true;

  static ServiceProvider of(BuildContext context) {
    return  (context.inheritFromWidgetOfExactType(ServiceProvider));
  }

}

尝试接收abc继承的窗口小部件时出现错误。请我错过什么。

我只能通过

收到此错误
  final abc = ServiceProvider.of(context).serviceListBloc;

但不使用

  final abc = ServiceProvider.of(context);

并且我需要指向块来调用我的方法

1 个答案:

答案 0 :(得分:0)

在第一种情况下您没有例外,因为您可能正在将null分配给abc(可以调试检查)。这不是无效的指令。但是,在第二种情况下,您尝试执行类似null.serviceListBloc的操作,这将触发异常。

通过查看您的代码,您似乎并没有ServiceProvider的祖先,您甚至在构建MaterialApp之前就试图访问它,而ServiceProvider具有s作为其后代树中的子代之一。