Flutter:如何确保异步函数中的变量正确初始化?

时间:2020-04-28 11:22:10

标签: flutter asynchronous

我有这段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初始化之前?

1 个答案:

答案 0 :(得分:1)

在onTap函数中使用异步并等待。

代码看起来像这样。

onTap: ()async {
        // The async function called here.
        await readJSONFile(_songName);

        Navigator.push( /* some code here */ );
      },