【发布时间】: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);
我需要指向该集团来调用我的方法
【问题讨论】: