我在Flutter中有一个statefulWidget
,如下所示:
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
,但如果我继续并在selectedWord
中将hello
更改为hellos
,这不会更新屏幕,即使打开了热加载,它仍然显示hello
。我必须重新启动应用程序,这样它才会显示hellos
。我该怎么解决这个问题?
根据我的经验,热重载保持状态。是否尝试热重启?
参考您的评论,如果您想继续使用热重载,我建议您将变量提取到小部件本身(如果这是您的一个选项(,如下所示:
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(),
],
)),
);
}
}