0

我对颤振和飞镖仍然很陌生,但我目前正在尝试返回一个未来的小部件,它是我在 StatefulWidget 内的主要游戏,我想知道我是否需要使用未来的构建器,或者是否有其他方法可以做到这一点?

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

1 回答 1

0

您不能await在方法内部使用build。您可以改用FutureBuilder小部件:

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);
      },
    );
  }
}
于 2021-06-10T23:15:07.290 回答