【发布时间】:2020-05-07 00:42:12
【问题描述】:
我想请你帮忙。
我下面的示例代码旨在从子小部件更新父小部件的状态,同时更新子小部件的状态。 Parent Widget 的文本值会更新,同时还会更改 Child Widget 按钮的颜色。
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');
},
);
}
}
到目前为止,它能够做的是更新子小部件的颜色/状态,但是,父小部件似乎没有更新其状态。我的原始代码实际上只更新了 Parent 的 State 而不是 Parent 和 Child (相同的概念和关注点)。
上面的示例代码是我在问这里之前的初步研究结果的衍生产品。
我认为我的代码结构一定有问题,或者根据我的制作方式,这在 Flutter 的架构中是不可能的。如果可能的话,你能给我你对具有相同行为的东西的建议吗? (更新父子状态)
抱歉,我是这种类型的编程和架构的新手。
【问题讨论】:
标签: flutter