我希望你能帮忙翻译以下内容,谢谢。
下面的示例代码旨在从子组件更新父组件的状态,同时也更新子组件的状态。父组件的文本值将会更新,同时也会改变子组件按钮的颜色。
import 'package:flutter/material.dart';
void main() => runApp(AppIndex());
class AppIndex extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: ParentWidget());
}
}
class ParentWidget extends StatefulWidget {
@override
_ParentWidgetState createState() => _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
String _textValue = 'Old Value';
callback(newValue){
setState(() {
_textValue = newValue;
});
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Text(_textValue),
ChildWidget(),
],
);
}
}
class ChildWidget extends StatefulWidget {
String textValue;
Function callback;
ChildWidget({this.textValue, this.callback});
@override
_ChildWidgetState createState() => _ChildWidgetState();
}
class _ChildWidgetState extends State<ChildWidget> {
bool buttonState = false;
@override
Widget build(BuildContext context) {
return RaisedButton(
color: buttonState == true ? Colors.greenAccent : Colors.redAccent,
child: Text('Update State'),
onPressed: () {
setState(() {
if (buttonState == false) {
buttonState = true;
} else if (buttonState == true) {
buttonState = false;
}
});
widget.callback('New Value');
},
);
}
}
到目前为止,这个程序可以更新子小部件的颜色/状态,但是父小部件似乎没有更新其状态。我的原始代码只更新了父级的状态,而不是父级和子级(相同的概念和关注点)。上面的示例代码是在我提问之前进行初始研究的结果。
我认为我的代码结构有问题,或者根据我的制作方式,Flutter架构中不可能实现这一点。如果可能的话,您能否为我推荐具有相同行为的解决方案?(更新父级和子级状态)
抱歉,我对这种类型的编程和架构还很陌生。