首页 > 解决方案 > 如何在 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(),
      ],
    ),
  );
}

标签: flutterdart

解决方案


我相信 Provider 是在 Flutter Application 中管理状态的推荐方法,并在 Google IO 上介绍过,并且在Flutter 状态管理文档中处于状态管理堆栈的顶部

服务作为我的提供者...

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 文档示例


推荐阅读