[英]Screen not updating in a statefulWidget in Flutter
I have a statefulWidget
in Flutter like this:我在 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)));
}
}
The problem is that when I first launch the app with this widget, I can see hello
on the screen, but if I go on and change hello
to hellos
in selectedWord
, that does not update the screen and it still shows me hello
even though the hot reload is turned on.问题是,当我第一次使用这个小部件启动应用程序时,我可以在屏幕上看到
hello
,但是如果我继续在selectedWord
中将hello
更改为hellos
,这不会更新屏幕,它仍然显示我hello
即使热重载已开启。 I have to go and restart the app so it shows me hellos
.我必须去重新启动应用程序,以便它向我显示
hellos
。 How could I fix this?我怎么能解决这个问题?
In my experience, hot reload keeps states.根据我的经验,热重载会保持状态。 Try hot restart instead?
试试热重启?
Referring to your comment, if you want to keep using hot reload, I suggest you pull out the variable to your widget itself (if that is an option for you), like this:参考您的评论,如果您想继续使用热重载,我建议您将变量拉出到您的小部件本身(如果这是您的选择),如下所示:
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(),
],
)),
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.