Reputation: 27
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?
Upvotes: 0
Views: 1513
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
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
Reputation: 1090
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) {
print(id); // print here
return ViewPostScreen(
id: id,
);
}
),
);
},
Upvotes: 0