Use async function with RaisedButton onPressed() to pass object to another route


I want to be able to press a button an Navigate to another screen while passing an object as an argument. The object is created with the getPlayer() function that is within a different dart file; hence, the async function. Whenever I run the code I get the error:

Error: This expression has type 'void' and can't be used. onPressed: loadPlayerCard('nebula'),

Here is the code:

    class _HomeState extends State<Home> {

  List<Player> players;

   void loadPlayerCard (String playerName) async {
    Player player = await getPlayer(playerName);

    Navigator.pushNamed(context, '/playerCard', arguments: player);

  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[900],
      appBar: AppBar(
        title: Text('Smash Tracker'),
        centerTitle: true,
        backgroundColor: Colors.grey[850],
        elevation: 0,
      body: Center(
        child: RaisedButton.icon(
            onPressed: loadPlayerCard('nebula'), //This is where the error message points to 
            icon: Icon(Icons.touch_app),
            label: Text('Nebula'),

Any help is appreciated!


wrap it with brackets as follows

  onPressed:() async { loadPlayerCard('nebula'); }, // Fix for the issue
  icon: Icon(Icons.touch_app),
  label: Text('Nebula'),

Answered By – griffins

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *