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