0

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

1
  • 1
    post error message Commented Apr 9, 2020 at 12:37

3 Answers 3

1

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);
  }
}
Sign up to request clarification or add additional context in comments.

5 Comments

can I use this method in _ViewPostScreenState?
Yes, you can, I just added full solution. Please take a look.
actually he doesn't need to create method method to access widget.id from state class as mentioned in your answer
Yes you're right, he can do that inside any method, I just created a standalone method to make things look easy.
Thanks. also, I need to call a method in initState(). Thanks again
0
onTap: () {
      Navigator.push(
        context,
            MaterialPageRoute(
                 builder: (_) {
print(id); // print here
                      return ViewPostScreen(
                       id: id,
                      );
                   }
                 ),
               );
            },

1 Comment

need to print on other page
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.