在这种情况下,建议使用InheritedWidget。
documentation for InheritedWidget 很全面,包括一个video from the Flutter team。
首先,您可能想要创建一个类来保存您要共享的数据。
import 'dart:async';
class MyInheritedWidgetData {
var sharedData;
int someCount;
String someMessage;
final StreamController _streamController = StreamController.broadcast();
Stream get stream => _streamController.stream;
Sink get sink => _streamController.sink;
}
我刚刚在这个类中添加了一堆变量。你可以用任何你想要的东西来填充它。
现在,您还希望拥有一个包含此数据类的InheritedWidget。
class MyInheritedWidget extends InheritedWidget {
final MyInheritedWidgetData data;
MyInheritedWidget({
Key key,
@required Widget child,
}) : assert(child != null),
data = MyInheritedWidgetData(),
super(key: key, child: child);
static MyInheritedWidgetData of(BuildContext context) => (context.inheritFromWidgetOfExactType(MyInheritedWidget) as MyInheritedWidget).data;
@override
bool updateShouldNotify(MyInheritedWidget old) => false;
}
您需要将此MyInheritedWidget 放在小部件树的顶部或至少在您谈到的父小部件之上。下面应该说明必要的小部件层次结构。
MyInheritedWidget
TabBarView
InputManagment
InfiniteListView
// in your build function this would be `body: MyInheritedWidget(child: TabBarView(...))`
现在,您可以在任何子小部件中使用 MyInheritedWidget.of(context) 轻松访问您的数据类。
您可能需要考虑使用流来连续发送和收听“数据流”。但是,这也只是数据类的一部分。为了给你一个想法,我在示例数据类中包含了流变量。您可以使用MyInheritedWidget.of(context).sink.add(..) 添加数据,并使用MyInheritedWidget.of(context).stream 将您的流提供给StreamBuilder。
这些只是解释在小部件之间共享数据所需的示例。您可以阅读documentation 了解更多信息和更高级的用例。