flutter - 如何在 Flutter 中的选项卡之间发送数据?
问题描述
我有一个带有 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(),
],
),
);
}
解决方案
我相信 Provider 是在 Flutter Application 中管理状态的推荐方法,并在 Google IO 上介绍过,并且在Flutter 状态管理文档中处于状态管理堆栈的顶部
- Flutter 中的 GoogleI/O实用状态管理视频 (Google I/O'19)
服务作为我的提供者...
import 'dart:collection';
import 'package:flutter/material.dart';
class Item {
String name;
num price;
Item(this.name, this.price);
}
class CartModel extends ChangeNotifier {
/// Internal, private state of the cart.
final List<Item> _items = [];
/// An unmodifiable view of the items in the cart.
UnmodifiableListView<Item> get items => UnmodifiableListView(_items);
/// The current total price of all items (assuming all items cost $42).
/// int get totalPrice => _items.length * 42;
/// Adds [item] to cart. This is the only way to modify the cart from outside.
void add(Item item) {
_items.add(item);
// This call tells the widgets that are listening to this model to rebuild.
notifyListeners();
}
}
设置访问状态*
void main() => runApp(
ChangeNotifierProvider<CartModel>(
child: TabBarDemo(),
builder: (BuildContext context) {
return CartModel();
},
),
);
从顶层访问状态以在选项卡标题中显示计数
class TabBarDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
var count = Provider.of<CartModel>(context).items.length;
将商品添加到购物车时从第一个选项卡访问状态
RaisedButton(
child: Text("Add Item"),
onPressed: () async {
final form = _formKey.currentState;
form.save();
if (form.validate()) {
Provider.of<CartModel>(context)
.add(new Item(_name, num.parse(_price)));
} else {
print('validate failed');
}
_formKey.currentState.reset();
})
请参阅此处的完整示例:https ://github.com/aaronksaunders/flutter_simple_tabs ,此代码基于Flutter 文档示例
推荐阅读
- ios - 具有 minimumscaleFactor 的 SwiftUI 文本始终减少文本
- java - 三元运算符我试图获取用户输入的扫描仪结果,但它不像我想的那样
- c++ - 错误:使用未声明的标识符 VS 代码
- java - 如何使用 Java 驱动程序从 MongoDB 文档中动态获取 ArrayOfObjects 的值
- python - 为什么这个问题的答案是假的?
- python - 此代码无法用随机符号替换坏词
- micronaut - 是否可以跳过某些 HTTP 状态代码的 Micronaut 断路器?
- c - 链接到包含全局变量的静态库时,clang 和 gcc-10 之间的行为不同
- php - 发送网络表单:不允许信封发件人
- angular - 动态加载页面时如何导航回上一页而不重新加载