更改为 'Widget' 的子类型。未来 <Widget> 构建(BuildContext 上下文)异步 {

Change to a subtype of 'Widget'. Future<Widget> build(BuildContext context) async {

我对 flutter 和 dart 还是很陌生,但我目前正在尝试 return 未来的小部件,这是我在 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,
    );
  }
}

您不能在 build 方法中使用 await。您可以改用 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);
      },
    );
  }
}