这是场景的简化版本:
class ParentWdiegt extends StatelessWidget{
//
//
floatinActionButton: FloatingActionButtonWidget(onPressed:()=>CustomWidgetState.someMethod(someValue))
//
//somewhere in the ParentWidget tree
child: CustomWidget() //is stateful
}
自定义小部件状态
class CustomWidgetState extends State<CustomWidget>{
//trigger this function when FAB is pressed in parent widget
someMethod(SomeValue) {//}
}
有没有什么方法可以在不使用 InheritedWidget
的情况下在按下 FAB 时将要触发的状态对象中的 someMethod
公开?
最佳答案
而 GlobalKey
允许轻松访问任何小部件的状态;躲开它。
小部件不应直接与其他小部件交互。这是 Flutter 的核心原则之一。
Flutter 使用响应式编程。小部件通过提交事件相互通信。不是通过直接编辑所需的小部件。
明显的好处是小部件保持独立。并且可能有几十个小部件可以使用相同的原理相互通信。
我已经做了一个例子here关于如何使两个不同的小部件共享一个共同的可编辑值。
如果你想调用方法,这使用相同的原则:一个 Listenable
或 Stream
在小部件之间共享。但不使用 AnimatedWidget
或 StreamBuilder
进行监听。
相反,我们将手动进行监听(这需要更多样板)来触发自定义函数。
这是一个使用 Stream
的示例。
import 'dart:async';
import 'package:flutter/material.dart';
class ParentWidget extends StatefulWidget {
@override
_ParentWidgetState createState() => _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
final changeNotifier = new StreamController.broadcast();
@override
void dispose() {
changeNotifier.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
return new Column(
children: <Widget>[
new AnotherWidget(
shouldTriggerChange: changeNotifier.stream,
),
new RaisedButton(
child: new Text("data"),
onPressed: () => changeNotifier.sink.add(null),
)
],
);
}
}
class AnotherWidget extends StatefulWidget {
final Stream shouldTriggerChange;
AnotherWidget({@required this.shouldTriggerChange});
@override
_AnotherWidgetState createState() => _AnotherWidgetState();
}
class _AnotherWidgetState extends State<AnotherWidget> {
StreamSubscription streamSubscription;
@override
initState() {
super.initState();
streamSubscription = widget.shouldTriggerChange.listen((_) => someMethod());
}
@override
didUpdateWidget(AnotherWidget old) {
super.didUpdateWidget(old);
// in case the stream instance changed, subscribe to the new one
if (widget.shouldTriggerChange != old.shouldTriggerChange) {
streamSubscription.cancel();
streamSubscription = widget.shouldTriggerChange.listen((_) => someMethod());
}
}
@override
dispose() {
super.dispose();
streamSubscription.cancel();
}
void someMethod() {
print('Hello World');
}
@override
Widget build(BuildContext context) {
return Container();
}
}
在本例中,每当点击 _ParentWidgetState
实例化的 RaisedButton
时,都会调用 AnotherWidget
的 someMethod
被执行。
https://stackoverflow.com/questions/50733840/