使用带有 RaisedButton onPressed() 的异步函数将对象传递到另一条路线
Use async function with RaisedButton onPressed() to pass object to another route
我希望能够在将对象作为参数传递时按下按钮并导航到另一个屏幕。该对象是使用不同 dart 文件中的 getPlayer() 函数创建的;因此,异步功能。每当我 运行 代码时,我都会收到错误消息:
Error: This expression has type 'void' and can't be used. onPressed: loadPlayerCard('nebula'),
代码如下:
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'),
),
),
);
}
}
感谢任何帮助!
用括号括起来如下
RaisedButton.icon(
onPressed:() async { loadPlayerCard('nebula'); }, // Fix for the issue
icon: Icon(Icons.touch_app),
label: Text('Nebula'),
),
您可以像这样简单地使用内联箭头函数 Lexical closures。
RaisedButton.icon(
onPressed: () => loadPlayerCard('nebula'), // Solved
icon: Icon(Icons.touch_app),
label: Text('Nebula'),
),
我希望能够在将对象作为参数传递时按下按钮并导航到另一个屏幕。该对象是使用不同 dart 文件中的 getPlayer() 函数创建的;因此,异步功能。每当我 运行 代码时,我都会收到错误消息:
Error: This expression has type 'void' and can't be used. onPressed: loadPlayerCard('nebula'),
代码如下:
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'),
),
),
);
}
}
感谢任何帮助!
用括号括起来如下
RaisedButton.icon(
onPressed:() async { loadPlayerCard('nebula'); }, // Fix for the issue
icon: Icon(Icons.touch_app),
label: Text('Nebula'),
),
您可以像这样简单地使用内联箭头函数 Lexical closures。
RaisedButton.icon(
onPressed: () => loadPlayerCard('nebula'), // Solved
icon: Icon(Icons.touch_app),
label: Text('Nebula'),
),