我有这段Flutter代码。
class SongItem extends StatelessWidget {
final String _songName;
final String _songNumber;
// This need to be initialized in the readJSONFile() function.
String _songLyrics;
SongItem(
this._songNumber,
this._songName
);
void readJSONFile(String songName) async {
String song = await rootBundle.loadString(songName);
_songLyrics = song;
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
// The async function called here.
readJSONFile(_songName);
Navigator.push( /* some code here */ );
},
child: Container( /* some code here */ ),
);
}
}
运行此代码时,_songLyrics
为空。我知道这与readJSONFile()是异步的这一事实有关。在这种情况下,如何强制对readJSONFile()函数的调用等待_songLyrics
初始化之前?
答案 0 :(得分:1)
在onTap函数中使用异步并等待。
代码看起来像这样。
onTap: ()async {
// The async function called here.
await readJSONFile(_songName);
Navigator.push( /* some code here */ );
},