Umaiz Khan
Umaiz Khan

Reputation: 27

Flutter how to print value pass through screen?

I am passing value between 2 screens I need to know how can I simply print value?

This is how I am sending value

onTap: () {
      Navigator.push(
        context,
            MaterialPageRoute(
                 builder: (_) => ViewPostScreen(
                   id: id,
                  ),
                 ),
               );
            },

This is my second page

class ViewPostScreen extends StatefulWidget {
  final int id;
  ViewPostScreen({Key key, @required this.id}) : super(key: key);

  @override
  _ViewPostScreenState createState() => _ViewPostScreenState();
}

class _ViewPostScreenState extends State<ViewPostScreen> {
}

I need to print the value of id in _ViewPostScreenState I try with simple print but showing error anyone can help?

enter image description here

Upvotes: 0

Views: 1513

Answers (3)

wxker
wxker

Reputation: 1896

You can access the widget's attributes from the State using widget

print(widget.id.toString());

You cannot call the print function in the class body. It needs to be within a function. You can use initState as it is the first function that runs.

void initState() {
    super.initState();
    print(widget.id.toString());
}

Note that you will also need a build method in your State class

Upvotes: 0

CopsOnRoad
CopsOnRoad

Reputation: 267404

The problem is you are not using print inside a method rather at the class level. Create a method and then use print inside it.

void method() {
  print(...);
}

Full solution:

class ViewPostScreen extends StatefulWidget {
  final int id;
  ViewPostScreen({Key key, @required this.id}) : super(key: key);

  @override
  _ViewPostScreenState createState() => _ViewPostScreenState();
}

class _ViewPostScreenState extends State<ViewPostScreen> {
  void method() {
    print(widget.id);
  }
}

Upvotes: 1

ifredom
ifredom

Reputation: 1090

onTap: () {
      Navigator.push(
        context,
            MaterialPageRoute(
                 builder: (_) {
print(id); // print here
                      return ViewPostScreen(
                       id: id,
                      );
                   }
                 ),
               );
            },

Upvotes: 0

Related Questions