Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

widget variable is null flutter

Tags:

flutter

I have a statefull widget

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;
  }
}

But on the line widget.notify.stream.listen(update); it catches the exception "The getter 'notify' was called on null." Why would widget be null? I print out the List the Periods are part of, but all of them are initialized properly.

like image 526
J. Aarts Avatar asked Sep 19 '25 01:09

J. Aarts


1 Answers

Don't use the constructor. Instead use initState

class Foo extends State<Bar> {
  @override
  void initState() {
    // widget is not null here
  }
}
like image 191
Rémi Rousselet Avatar answered Sep 21 '25 16:09

Rémi Rousselet