[英]Stateful Widget child is not updated
有两个有状态的小部件。 MyHomePage的状态包含计数器。 MyHomePage将内容包装在第二个有状态小部件SubPage中。 SubPage有一个子窗口小部件,其中包含MyHomePage中的数据。
为了澄清问题,当计数器更改时,SubPage子项内部的第一个textwidget不会更新。
SubPage外部的textwidget按预期递增。
如果我们想要更新内部有状态窗口小部件的内容,我们该怎么办?
我们必须在那里使用有状态的小部件。 在实际应用程序中,这个小部件有一个真实的用例。
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: Column(
children: <Widget>[
SubPage(
child: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
'You have pushed the button this many times:',
),
new Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
),
new Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
floatingActionButton: new FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: new Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
class SubPage extends StatefulWidget {
SubPage({Key key, this.child}) : super(key: key);
final Widget child;
@override
SubPageState createState() => new SubPageState(child);
}
class SubPageState extends State<SubPage> {
final Widget child;
SubPageState(this.child);
@override
Widget build(BuildContext context) {
print("subpage build");
return this.child;
}
}
您不必将child
设置为状态字段。 实际上它是这个错误的原因。 这里有工作代码
class SubPage extends StatefulWidget {
SubPage({Key key, this.child}) : super(key: key);
final Widget child;
@override
SubPageState createState() => new SubPageState();
}
class SubPageState extends State<SubPage> {
@override
Widget build(BuildContext context) {
return widget.child;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.