我正在尝试将文本从子窗口小部件设置为父窗口小部件。但是文本未反映在父窗口小部件中。
试图也使用setState()但仍然无法获得预期的结果。
以下是我的代码:
void main() => runApp(new TestApp()); class TestApp extends StatefulWidget { @override _TestState createState() => new _TestState(); } class _TestState extends State<TestApp>{ String abc = ""; @override Widget build(BuildContext context) { return new MaterialApp( home: new Scaffold( body: new Column( children: <Widget>[ new Text("This is text $abc"), TestApp2(abc) ], ), ), ); } } class TestApp2 extends StatefulWidget { String abc; TestApp2(this.abc); @override _TestState2 createState() => new _TestState2(); } class _TestState2 extends State<TestApp2>{ @override Widget build(BuildContext context) { return new Container( width: 150.0, height: 30.0, margin: EdgeInsets.only(top: 50.0), child: new FlatButton( onPressed: (){ setState(() { widget.abc = "RANDON TEXT"; }); }, child: new Text("BUTTON"), color: Colors.red, ), ); } }
我想念什么吗?
在您的示例中,进行了一些假设。我将尝试一一删除。
abc
void main() { String abc = "oldValue"; changeIt(abc); print(abc); // oldValue } void changeIt(String abc) { abc = "newValue"; print(abc); //newValue }
假设第一个错误(出于理解目的)。然后更改abcin 的值将更改abcin 的值。但是如果setState不在父级内部调用,父级将不会反映该更改。在您的情况下,如果您按以下方式更改代码,则它将仅在单击时更改按钮文本(因为调用child的setState)。
setState
new FlatButton( onPressed: () { setState( () { widget.abc = "RANDON TEXT"; }, ); }, child: new Text(widget.abc), // setting the text based on abc color: Colors.red,
),
而不是使用的globalState,这将是非常困难的,因为应用程序的增长来维持/调试,我会建议使用callbacks。请参考以下代码。
globalState
callbacks
void main() => runApp(new TestApp()); class TestApp extends StatefulWidget { @override _TestState createState() => new _TestState(); } class _TestState extends State<TestApp> { String abc = "bb"; callback(newAbc) { setState(() { abc = newAbc; }); } @override Widget build(BuildContext context) { var column = new Column( children: <Widget>[ new Text("This is text $abc"), TestApp2(abc, callback) ], ); return new MaterialApp( home: new Scaffold( body: new Padding(padding: EdgeInsets.all(30.0), child: column), ), ); } } class TestApp2 extends StatefulWidget { String abc; Function(String) callback; TestApp2(this.abc, this.callback); @override _TestState2 createState() => new _TestState2(); } class _TestState2 extends State<TestApp2> { @override Widget build(BuildContext context) { return new Container( width: 150.0, height: 30.0, margin: EdgeInsets.only(top: 50.0), child: new FlatButton( onPressed: () { widget.callback("RANDON TEXT"); //call to parent }, child: new Text(widget.abc), color: Colors.red, ), ); } }