我使用下面的示例来测试和学习如何从子小部件调用父函数。
当您单击 TestButton
时, countRefresh
函数被调用,变量 count
增加 1。
现在,每次单击按钮时都会更改颜色(蓝色或红色)。
问题 :说我希望颜色根据 count
周围的一些逻辑而改变变量,我如何访问 count
来自 TestButton
内的变量小部件?
例如。如果 count
是三的倍数,则按钮应为红色,否则为蓝色。
我读过 InheritedWidgets,但似乎变量在 InheritedWidgets 中必须是 final 的(如果我没有在 int count = 0;
之前放置 final,我会收到“此类被标记为不可变”消息错误)。
但基于这个例子,我需要 count
每次单击按钮时更改。
InheritedWidgets 的替代品是什么?
import 'package:flutter/material.dart';
class Test extends StatefulWidget {
static const String id = 'test';
@override
_TestState createState() => _TestState();
}
class _TestState extends State<Test> {
int count = 0;
Color color = Colors.red;
void refreshCount() {
setState(() {
count += 1;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child:
Text('The button was pressed $count time${count == 1 ? '' : 's'}'),
),
floatingActionButton: TestButton(
color: color,
notifyParent: refreshCount,
),
);
}
}
class TestButton extends StatefulWidget {
TestButton({
@required this.color,
@required this.notifyParent,
});
final Color color;
final void Function() notifyParent;
@override
_TestButtonState createState() => _TestButtonState();
}
class _TestButtonState extends State<TestButton> {
Color color;
void initState() {
color = widget.color;
super.initState();
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
widget.notifyParent();
setState(() {
color = color == Colors.red ? Colors.blue : Colors.red;
});
},
child: Container(
child: Icon(
Icons.add,
size: 80,
),
color: color,
),
);
}
}
最佳答案
I want the color to change based on some logic around the count variable, how can I access the count variable from within the TestButton widget? E.g. if count is a multiple of three then the button should be red, otherwise blue.
您需要通过
count
到 child 身上,让 child 根据那个值(value)来建立自己。不要尝试访问父小部件。在声明式编程中,您只能更新状态和重建树。
这是一个关于 Flutter 状态管理的好视频:https://www.youtube.com/watch?v=HrBiNHEqSYU
关于Flutter:如何获取父小部件变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60502447/