我有一个有状态的小部件
class Period extends StatefulWidget{
final StreamController<List<dynamic>> notify = StreamController<List<dynamic>>();
final int period;
Period(List<dynamic> data, this.period){
notify.sink.add(data);
print("created new Period:");
print(period);
}
void dispose() {
notify.close();
}
@override
_PeriodState createState() => _PeriodState();
}
class _PeriodState extends State<Period> {
bool isNull = true;
bool isListening = false;
List<Widget> lessons;
_PeriodState(){
lessons = [(genTime())];
widget.notify.stream.listen(update);
isListening = true;
}
}
但在 widget.notify.stream.listen(update);
行中,它捕获了异常“The getter 'notify' was called on null.”
为什么小部件为空?我打印出周期所属的列表,但所有周期都已正确初始化。
最佳答案
不要使用构造函数。而是使用 initState
class Foo extends State<Bar> {
@override
void initState() {
// widget is not null here
}
}
关于flutter - 小部件变量为空 flutter ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55030980/