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

7.4k Views Asked by At

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);
    players.add(player);

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

  @override
  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!

2

There are 2 best solutions below

0
On BEST ANSWER

wrap it with brackets as follows

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

You can simply use Inline Arrow Function Lexical closures like this way.

RaisedButton.icon(
    onPressed: () => loadPlayerCard('nebula'), // Solved 
    icon: Icon(Icons.touch_app),
    label: Text('Nebula'),
),