0

I am still pretty new to flutter and dart but I am currently trying to return a future widget that is my main game inside of a StatefulWidget and I am wondering if I need to use a future builder or if there is another way to do it?

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:untitled2/screens/game.dart';

class GamePlay extends StatefulWidget {


  GamePlay({Key key}) : super(key: key);

  @override
  _GamePlayState createState() => _GamePlayState();
}

class _GamePlayState extends State<GamePlay> {



  @override
  Widget build(BuildContext context)  async { // THIS IS WHERE IT SAYS THE PROBLEM IS

    SharedPreferences storage = await SharedPreferences.getInstance();
    MainGame mainGame = MainGame(storage);

    return Scaffold(
      body: mainGame.widget,
    );
  }
}
  • I really recommend you to use the 1.0.0 branch instead of 0.29.4 since v1 is very soon released and 0.29.4 is not getting any more updates. https://pub.dev/packages/flame/versions/1.0.0-releasecandidate.11 – spydon Jun 11 '21 at 07:40
  • Okay thanks I will make sure to switch it over! – JackOLack413 Jun 11 '21 at 19:57

1 Answers1

1

You can't use await inside the build method. You can use a FutureBuilder widget instead:

class _GamePlayState extends State<GamePlay> {
  // Create a property variable to be updated
  SharedPreferences _storage;

  // Create a future to store the computation
  Future<void> _future;

  @override
  void initState() {
    super.initState();
    // When creating the widget, initialize the future
    // to a method that performs the computation
    _future = _compute();
  }

  Future<void> _compute() async {
    // Make your asynchronous computation here
    _storage = await SharedPreferences.getInstance();
  }

  @override
  Widget build(BuildContext context) async {
    // Use a FutureBuilder to display to the user a progress
    // indication while the computation is being done
    return FutureBuilder(
      future: _future,
      builder: (context, snapshot) {
        // If snapshot is not ready yet, display the progress indicator
        if (snapshot.connectionState == ConnectionState.waiting)
          return Center(child: CircularProgressIndicator());

        // If it's ready, use the property
        final SharedPreferences storage = _storage;
        final MainGame mainGame = MainGame(storage);
        return Scaffold(body: mainGame.widget);
      },
    );
  }
}
enzo
  • 9,861
  • 3
  • 15
  • 38