【问题标题】:Getter was called on null while accessing inherited widget访问继承的小部件时在 null 上调用 Getter
【发布时间】:2018-12-22 22:36:20
【问题描述】:

我在 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);

我需要指向该集团来调用我的方法

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

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

    通过查看您的代码,您似乎没有 ServiceProvider 祖先,您甚至在构建 MaterialApp 之前就尝试访问它,而 ServiceProvider 又是它在后代树中的一个孩子。

    【讨论】:

    • 谢谢。您的解释有助于破译问题的真正含义。我没有正确创建继承的小部件(ServiceProvider)祖先。
    猜你喜欢
    • 2020-04-16
    • 1970-01-01
    • 2019-12-23
    • 2020-08-09
    • 2020-06-18
    • 1970-01-01
    • 2021-05-24
    • 2016-12-03
    • 1970-01-01
    相关资源
    最近更新 更多