Home > Mobile >  Can't pass argument from parent to child widget
Can't pass argument from parent to child widget

Time:10-14

I can't seem to pass a simple int for some reason. This is what I'm doing:

print("here we have ${widget.which}"); //prints here we have 1
    return Scaffold(
    body:ScrollablePositionedListPage(neducem:widget.which)


class ScrollablePositionedListPage extends StatefulWidget {
  late int neducem;
  ScrollablePositionedListPage({required int neducem});

  @override
  ScrollablePositionedListPageState createState() {
    print("and here we have $neducem"); //this line throws exception : Field 'neducem' has not been initialized
    return ScrollablePositionedListPageState();}

What gives?

CodePudding user response:

Your constructor is not set corectly.

ScrollablePositionedListPage({required int neducem});

To fix it:

ScrollablePositionedListPage({required this.neducem}); # add this

or

ScrollablePositionedListPage({required int neducem}): this.neducem=neducem; # add this

More about constructors https://dart.dev/guides/language/language-tour#constructors

CodePudding user response:

You are not using constructors properly. That data you are passing isn't being saved anywhere. Most of the times you can solve this with final fields and on the constructor use this.which. That way when you fill this, that data will be filled correctly.

print("here we have ${widget.which}"); //prints here we have 1
    return Scaffold(
    body:ScrollablePositionedListPage(neducem:widget.which)


class ScrollablePositionedListPage extends StatefulWidget {
  final int neducem;
  ScrollablePositionedListPage({required this.neducem});

  @override
  ScrollablePositionedListPageState createState() {
    print("and here we have $neducem"); //It should work
    return ScrollablePositionedListPageState();}

From your approach, if you ever need to change neducem which is not usually the case you may try something like this manual approach of assignining variables:

print("here we have ${widget.which}"); //Now should work
    return Scaffold(
    body:ScrollablePositionedListPage(neducem:widget.which)


class ScrollablePositionedListPage extends StatefulWidget {
  late int neducem;
  ScrollablePositionedListPage({required int neducem}) : this.neducem = neducem;

  @override
  ScrollablePositionedListPageState createState() {
    print("and here we have $neducem"); //Now should work
    return ScrollablePositionedListPageState();}

Tell me if it works.

  • Related