Widget变量为空Flutter。

4

我有一个有状态的小部件

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."。为什么widget会是null?我打印输出了包含Periods的List,但它们都已经被正确初始化了。

1个回答

8
不要使用构造函数,而是使用 initState
class Foo extends State<Bar> {
  @override
  void initState() {
    // widget is not null here
  }
}

1
为什么构造函数中的 widget 为空? :0 - fr3ddie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接