gpt4 book ai didi

dart - 触发从小部件到状态对象的函数

转载 作者:IT老高 更新时间:2023-10-28 12:34:49 28 4
gpt4 key购买 nike

这是场景的简化版本:

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关于如何使两个不同的小部件共享一个共同的可编辑值。

如果你想调用方法,这使用相同的原则:一个 ListenableStream 在小部件之间共享。但不使用 AnimatedWidgetStreamBuilder 进行监听。相反,我们将手动进行监听(这需要更多样板)来触发自定义函数。

这是一个使用 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 时,都会调用 AnotherWidgetsomeMethod被执行。

关于dart - 触发从小部件到状态对象的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50733840/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com