我有一个带有 2 个选项卡的 Flutter 应用程序:一个用于管理和接收连续的数据流,另一个选项卡显示传入的数据。
如何将数据从第一个选项卡传递到第二个选项卡?我看到的大多数帖子都是关于在父子之间传递数据,而不是在子与子之间传递数据。
我会使用 GlobalKey
吗?有更好的选择吗?
这是主要的构建函数:
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('some text'),
bottom: TabBar(
tabs: tabs,
controller: _tabController,
),
),
body: TabBarView(
controller: _tabController,
children: [
InputManagment(),
InfiniteListView(),
],
),
);
}
最佳答案
这种情况下,推荐使用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(..)
添加数据并将流提供给 StreamBuilder
使用 MyInheritedWidget.of(context).stream
。
这些只是示例,用于解释在小部件之间共享数据所需的内容。您可以通读 documentation获取更多信息和更高级的用例。
关于flutter - 如何在 Flutter 中的选项卡之间发送数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56657456/