Home > front end >  Null value in Flutter widget inside initState method
Null value in Flutter widget inside initState method

Time:02-05

It's the first time a use Flutter (2.8.1) and I'having problems trying to undestrand what's going wrong.

I have a Stateful widget like this:

class SimpleWidget extends StatefulWidget {
  const SimpleWidget({Key key, @required this.aValue}) : super(key: key);
  final Type2 aValue;
  @override
  _SimpleWidgetState createState() => _SimpleWidgetState();
}

class _SimpleWidgetState extends State<SimpleWidget> {
  Type1 from;
  Type1 to;

  @override
  void initState() {
    print('mounted: $mounted'); // true
    print('widget.aValue: ${widget.aValue}'); // null <-- WHY IS THIS NULL?

    super.initState();

    from = ...;
    to = ...;
  }
  ...
}

that I call in this way:

List<Type1> breakTimes = await showDialog(
  context: context,
  builder: (context) {
    print('currentElement.aValue: ${currentElement.aValue}'); // not null
    return SimpleWidget(aValue: currentElement.aValue);
  },
);

Why is widget.aValue == null in initInstance()? How can I solve it?

CodePudding user response:

There is wrong in your code :

Chane this to this:

class SimpleWidget extends StatefulWidget {
  final Type2 aValue; // initialize 1st
  const SimpleWidget({Key key, @required this.aValue}) : super(key: key);

  @override
  _SimpleWidgetState createState() => _SimpleWidgetState();
}
  •  Tags:  
  • Related