【发布时间】:2021-10-07 17:38:30
【问题描述】:
我正在学习颤振,我想将一个函数(在有状态类中)调用到另一个有状态类中。我到处搜索,但没有可靠的解决方案。任何人都可以建议或提供我调用该函数的正确方法吗?
【问题讨论】:
标签: flutter flutter-state flutter-functional-widget
我正在学习颤振,我想将一个函数(在有状态类中)调用到另一个有状态类中。我到处搜索,但没有可靠的解决方案。任何人都可以建议或提供我调用该函数的正确方法吗?
【问题讨论】:
标签: flutter flutter-state flutter-functional-widget
试试下面的代码希望对你有帮助:
用你的函数声明第一个有状态的类:
class MobileGraph extends StatefulWidget {
_MobileGraphState mobileGraph = _MobileGraphState();
@override
_MobileGraphState createState() => mobileGraph;
mobileGraphFunction() {
mobileGraph.mobileGraphFunction();
}
}
class _MobileGraphState extends State<MobileGraph> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: mobileGraphFunction(),
);
}
}
然后在其他有状态类中调用 mobileGraphFunction,例如:
class Graph extends StatefulWidget {
@override
_GraphState createState() => _GraphState();
}
class _GraphState extends State<Graph> {
MobileGraph mobileGraph;
@override
void initState() {
super.initState();
mobileGraph = MobileGraph();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'All Graphs',
style: TextStyle(fontSize: 25),
),
),
body: mobileGraph(),
);
}
}
【讨论】:
MobileGraph 里面的 mobileGraphFunction 类是 Widget
您需要访问 State 的实例才能调用其函数之一。在不了解您的用例的情况下,您可以创建一个控制器类。
class CounterController {
late Function increment();
late Function decrement();
}
然后将其作为参数传递给您的 Widget。
class CounterWidget extends StatefulWidget {
final CounterController? controller;
CounterWidget({this.controller});
}
然后分配initState中的函数。
class CounterWidgetState extends State<CounterWidget> {
int count = 0;
@override
void initState() {
widget.controller?.increment = increment;
widget.controller?.decrement = decrement;
}
void increment() {
setState(() => count++);
}
void decrement() {
setState(() => count--);
}
}
然后你终于可以调用函数了。
Row(
children: [
CounterWidget(controller: counterController),
TextButton(
child: const Text('+'),
onPressed: () => counterController.increment(),
),
TextButton(
child: const Text('-'),
onPressed: () => counterController.decrement(),
),
]
)
【讨论】: