0

statefulWidget在 Flutter 中有这样的:

class GameScreen extends StatefulWidget {
  @override
  GameScreenState createState() => GameScreenState();
}

class GameScreenState extends State<GameScreen> {
  List<String> selectedWord = ['h', 'e', 'l', 'l', 'o'];

  Widget _letterInput() {
    return Center(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          for (var letter in selectedWord) LetterInput(letter: letter)
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
          child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          _letterInput(),
        ],
      )),
    );
  }
}

class LetterInput extends StatelessWidget {
  LetterInput({this.letter});

  final String letter;

  @override
  Widget build(BuildContext context) {
    return Container(
        padding: EdgeInsets.fromLTRB(5, 0, 5, 0),
        decoration: BoxDecoration(
            border: BorderDirectional(
                bottom: BorderSide(width: 6.0, color: Colors.green))),
        child: Text(letter,
            textAlign: TextAlign.center,
            style:
                GoogleFonts.acme(fontSize: 28.0, fontWeight: FontWeight.w400)));
  }
}

问题是,当我第一次使用这个小部件启动应用程序时,我可以hello在屏幕上看到,但是如果我继续并更改hellohellosin selectedWord,那不会更新屏幕,hello即使打开了热重载它仍然会显示我. 我必须去重新启动应用程序,以便它显示给我hellos。我该如何解决这个问题?

4

1 回答 1

1

根据我的经验,热重载会保持状态。试试热重启?

参考您的评论,如果您想继续使用热重载,我建议您将变量拉出到您的小部件本身(如果这是您的选择),如下所示:

class GameScreen extends StatefulWidget {
  final List<String> selectedWord = ['h', 'e', 'l', 'l', 'o'];

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

class GameScreenState extends State<GameScreen> {
  Widget _letterInput() {
    return Center(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          for (var letter in widget.selectedWord) LetterInput(letter: letter)
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              _letterInput(),
            ],
          )),
    );
  }
}
于 2020-09-03T22:52:29.413 回答