Amani
Amani

Reputation: 18163

Flutter: How can I ensure proper initialization of a variable from asynchronous function?

I have this piece of Flutter code.

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 */ ),
    );
  }
}

When running this code the _songLyrics becomes null. I know this is related to the fact that readJSONFile() is asynchronous. In this case how can I force the call to readJSONFile() function to await until _songLyrics is initialized?

Upvotes: 0

Views: 27

Answers (1)

Sam Garg
Sam Garg

Reputation: 116

Use async and await in your onTap function.

The code would look like this.

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

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

Upvotes: 1

Related Questions