我想将对象列表添加到 firestore 文档中,-flutter

2024-05-12

我想将对象列表添加到 firestore 文档

我定义了产品数据模型

我还有类别数据模型

我想将类别列表添加到 firestore 中的产品文档中

我将类别添加到临时列表,然后将值放入product.categories 产品.类别=类别templist;

我使用了提供者状态

当我保存产品以 firestore 屏幕保持时,没有错误,但不保存

与产品形式相关的所有文件如下

    //product form dart file
import 'package:flutter/material.dart';
import '../api/categories_api.dart';
import '../models/category_model.dart';
import '../providers/category_provider.dart';
import '../api/products.dart';
import '../models/product_model.dart';
import '../providers/product_provider.dart';
import 'package:provider/provider.dart';

    class ProductForm extends StatefulWidget {
      final bool isUpdating;

      ProductForm({@required this.isUpdating});

      @override
      _ProductFormState createState() => _ProductFormState();
    }

    class _ProductFormState extends State<ProductForm> {
      final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
      final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

      ProductModel _currentProduct;
      CategoryModel _categoryDropdownValue;
      List<CategoryModel> _categoryTempList=[];

      @override
      void initState() {
        super.initState();
        ProductProvider productProvider = Provider.of<ProductProvider>(context, listen: false);
        CategoryProvider categoryProvider = Provider.of<CategoryProvider>(context, listen: false);
          getCategories(categoryProvider);

        if (productProvider.currentProduct != null) {
          _currentProduct = productProvider.currentProduct;
        } else {
          _currentProduct = new ProductModel();
        }
      }
      Widget _buildIdField() {
        return TextFormField(
          decoration: InputDecoration(labelText: 'Brand ID'),
          initialValue: _currentProduct.id,
          keyboardType: TextInputType.text,
          style: TextStyle(fontSize: 20),
          validator: (String value) {
            if (value.isEmpty) {
              return 'Product ID is required';
            }

             return null;
          },
          onSaved: (String value) {
            _currentProduct.id = value;
          },
        );
      }
      Widget _buildNameField() {
        return TextFormField(
          decoration: InputDecoration(labelText: 'Product name'),
          initialValue: _currentProduct.name,
          keyboardType: TextInputType.text,
          style: TextStyle(fontSize: 20),
          onSaved: (String value) {
            _currentProduct.name = value;
          },
        );
      }
      Widget _buildCategoryField() {
        CategoryProvider categoryProvider = Provider.of<CategoryProvider>(context);

        return DropdownButtonFormField<CategoryModel>(
              hint: Text('Select category'),
              value: _categoryDropdownValue,
              icon: Icon(Icons.arrow_downward),
              iconSize: 24,
              elevation: 16,
              style: TextStyle(color: Colors.deepPurple),

              onChanged: (CategoryModel newValue) {
                setState(() {
                  _categoryDropdownValue = newValue;
                });
              },
              items: categoryProvider.categoryList.map<DropdownMenuItem<CategoryModel>>((CategoryModel value) {
                return DropdownMenuItem<CategoryModel>(
                  value: value,
                  child: Text(value.name), 
                   );}
                  ).toList(),
              // onSaved: (CategoryModel value){
              //   _currentProduct.categories= _categoryTempList;
              //   print('save categories at dropdownmenu');
              // },
         );
       }

      _addCategories(CategoryModel category) {
        if (category!=null ){
          setState(() {
              _categoryTempList.add(category);
          });
        }
      }  
      _onProductUploaded(ProductModel product) {
        ProductProvider productProvider = Provider.of<ProductProvider>(context, listen: false);
        productProvider.addProduct(product);
        Navigator.pop(context);
      }

      _saveProduct() {
        print('saveProduct Called');
        if (!_formKey.currentState.validate()) {
          return;
        }

        _formKey.currentState.save();
        _currentProduct.categories= _categoryTempList ;
        print('form saved');

        uploadProduct(_currentProduct, widget.isUpdating, _onProductUploaded);
      }

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          key: _scaffoldKey,
          appBar: AppBar(title: Text('Product Form')),
          body: SingleChildScrollView(
            padding: EdgeInsets.all(32),
            child: Form(
              key: _formKey,
              autovalidate: true,
              child: Column(children: <Widget>[
                Text(
                  widget.isUpdating ? "Edit Product" : "Create Product",
                  textAlign: TextAlign.center,
                  style: TextStyle(fontSize: 30),
                ),
                SizedBox(height: 16),
            _buildIdField(),
                _buildNameField(),
                _buildCategoryField(),
             ButtonTheme(
                    child: RaisedButton(
                        child: Text('Add', style: TextStyle(color: Colors.white)),
                        onPressed: () => _addCategories(_categoryDropdownValue), 
                  ),),
                GridView.count(
                  shrinkWrap: true,
                  scrollDirection: Axis.vertical,
                  padding: EdgeInsets.all(8),
                  crossAxisCount: 3,
                  crossAxisSpacing: 4,
                  mainAxisSpacing: 4,
                  children: _categoryTempList
                      .map(
                        (CategoryModel value) => Card(
                          color: Colors.black54,
                          child: Center(
                            child: Text(
                              value.name,
                              style: TextStyle(color: Colors.white, fontSize: 14),
                            ),
                          ),
                        ),
                      )
                      .toList(),
                ),
              ]),
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: () {
              FocusScope.of(context).requestFocus(new FocusNode());
              _saveProduct();
            },
            child: Icon(Icons.save),
            foregroundColor: Colors.white,
          ),
        );
      }
    }

// 产品数据模型 dart 文件

import 'package:cloud_firestore/cloud_firestore.dart';
import 'category_model.dart';
    class ProductModel{
     static const ID = "id";
     static const NAME = "name";
     static const CATEGORIES= "categories";

     String id;
     String name;
     List<CategoryModel> categories;

    //  named constructure
    ProductModel();

    // deserialize data from firestore
      ProductModel.fromMap(Map<String, dynamic> data){
       id = data[ID];
       name = data[NAME];
       categories = data[CATEGORIES];
      }

      Map<String, dynamic> toMap() {
        return {
          'ID': id,
          'NAME':name,
          'CATEGORIES': categories,  
        };
      }
    }

// Category data model dart file
import 'package:cloud_firestore/cloud_firestore.dart';

    class CategoryModel{
     static const ID = "id";
     static const NAME = "name";
     String id;
     String name;

    //  named constructure
    CategoryModel();

    // deserialize data from firestore
      CategoryModel.fromMap(Map<String, dynamic> data){
       id = data[ID];
       name = data[NAME];
        }

      Map<String, dynamic> toMap() {
        return {
          'ID': id,
          'NAME':name,
        };
      }
    }


// Product provider dart file
import '../models/product_model.dart';
import 'package:flutter/material.dart';

    class ProductProvider with ChangeNotifier {
      List<ProductModel> _productList=[];
      ProductModel _currentProduct;
      List<ProductModel> _featuredProductList=[];



    //  getter
      List<ProductModel> get productList => _productList;
      List<ProductModel> get featuredProductList => _featuredProductList;
      ProductModel get currentProduct => _currentProduct;


    //  setter
      set productList(List<ProductModel> productList) {
        _productList = productList;
        notifyListeners();
      }

       set currentProduct(ProductModel product) {
        _currentProduct = product;
        notifyListeners();
      }

       addProduct(ProductModel product) {
        _productList.insert(0, product);
        notifyListeners();
      }

      deleteProduct(ProductModel product) {
        _productList.removeWhere((_product) => _product.id == product.id);
        notifyListeners();
      }

    }

// 类别提供者 dart 文件

import '../models/category_model.dart';
import 'package:flutter/material.dart';

class CategoryProvider with ChangeNotifier {
  List<CategoryModel> _categoryList=[];
  CategoryModel _currentCategory;
  List<CategoryModel> _featuredCategoryList=[];


//  getter
  List<CategoryModel> get categoryList => _categoryList;
  List<CategoryModel> get featuredCategoryList => _featuredCategoryList;
  CategoryModel get currentCategory => _currentCategory;


//  setter
  set categoryList(List<CategoryModel> categoryList) {
    _categoryList = categoryList;
    notifyListeners();
  }

   set featuredCategoryList(List<CategoryModel> featuredCategoryList) {
    _featuredCategoryList = featuredCategoryList;
    notifyListeners();
  }

   set currentCategory(CategoryModel category) {
    _currentCategory = category;
    notifyListeners();
  }

   addCategory(CategoryModel category) {
    _categoryList.insert(0, category);
    notifyListeners();
  }

  deleteCategory(CategoryModel category) {
    _categoryList.removeWhere((_category) => _category.id == category.id);
    notifyListeners();
  }

}

// 产品 api dart 文件 - firestore

import 'package:cloud_firestore/cloud_firestore.dart';
import '../providers/product_provider.dart';
import '../models/product_model.dart';

getProducts(ProductProvider productProvider) async{
  QuerySnapshot snapshot= await Firestore.instance.collection('products').getDocuments();
  List<ProductModel> _productList=[];
  snapshot.documents.forEach((document){
    ProductModel product= ProductModel.fromMap(document.data);
    _productList.add(product);
  });
  productProvider.productList=_productList;
}

uploadProduct(ProductModel product, bool isUpdating, Function productUploaded, {String imageUrl}) async {
  CollectionReference productRef = Firestore.instance.collection('products');

  if (imageUrl != null) {
    product.picture = imageUrl;
  }

  if (isUpdating) {
    await productRef.document(product.id).updateData(product.toMap());
    productUploaded(product);
    print('updated product with id: ${product.id}');
  } else {

    DocumentReference documentRef = await productRef.add(product.toMap());
    product.id = documentRef.documentID;
    print('uploaded successfully: ${product.toString()}');
    await documentRef.setData(product.toMap(), merge: true);
    productUploaded(product);
  }
}

deleteProduct(ProductModel product, Function productDeleted) async {
  await Firestore.instance.collection('products').document(product.id).delete();
  productDeleted(product);
}

我终于找到了在产品数据模型中将对象列表添加到 firestore 文档中的方法,它解决了问题:
'类别':categories.map((i) => i.toMap()).toList(),

ProductModel{
String id;
String name;
List<CategoryModel> categories

ProductModel.fromMap(Map<String, dynamic> data){
   id = data['id'];
   name= data['name'];
   categories = data['categories']; // here there is a problem, as i can't get product document with list of objects but i am working on it 
}
Map<String, dynamic> toMap() {
    return {
      'id': id,
      'name':name,
      'categories': categories.map((i) => i.toMap()).toList(),  // this worked well

};}}

CategoryModel{
String id;
String name;

CategoryModel.fromMap(Map<String, dynamic> data){
   id = data['id'];
   name= data['name'];
}
Map<String, dynamic> toMap() {
    return {
      'id': id,
      'name':name,
};}}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我想将对象列表添加到 firestore 文档中,-flutter 的相关文章

  • 按元组分隔符拆分列表

    我有清单 print L I WW am XX newbie YY ZZ You WW are XX cool YY ZZ 我想用分隔符将列表拆分为子列表 ZZ print new L I WW am XX newbie YY ZZ You
  • 如何在 Dart 中以正确的方式重定向和重新加载?

    在 Dart 中进行重定向和重新加载的首选方法是什么 我们是否只使用 window location href window location href 有几种不同的方法可以处理 URI 更改 每种方法都有自己的用途 当您想要将用户发送到另
  • 如何在没有 firebase 的情况下在 flutter 中显示推送通知?

    在我的 flutter 应用程序中 我必须在没有 firebase 的情况下显示推送通知 我的服务器会在点击特定 API 后向我发送一条消息 并且我希望将该消息显示为推送通知 你能告诉我一种方法如何在颤振中做到这一点吗 您可以使用本地通知插
  • 列表值的意外更改

    这是我的课 class variable object def init self name name alias parents values table name of the variable self name 这是有问题的函数 f
  • 如何将嵌套列表切片两次?

    使用嵌套列表 例如 ex list 1 2 3 4 5 6 7 8 9 我需要能够将此列表分割为 1 2 4 5 我一直在尝试 list ex list 2 2 但这不起作用 我显然做了一些非常错误的事情 但一直无法找到解决方案 因为由于某
  • 如何让flutter应用程序在android导航栏后面绘制并使导航栏完全透明?

    我想让我的 Flutter 应用程序占据 Android 中的整个屏幕 同时仍然显示状态栏和导航栏 并且两者都是透明的 以实现全屏 如下所示iOS https codelabs developers google com codelabs
  • 将 firestore 中的数据分配给变量

    我尝试使用 get doc 函数将 firestore 数据库中的变量分配给它们所尊重的值 我注意到它不会分配或更新这些值 我尝试使用异步和等待 但似乎无法使其工作 getFromDatabase nameOfCollection name
  • 使用 Firestore 和 Flutter 填充数据表(使用 StreamBuilder)

    如何使用 StreamBuilder 填充数据表 下面是我的代码 new StreamBuilder stream widget returnStreamWithActiveKeysOnly builder BuildContext con
  • 如何设置行高 Sencha Touch List

    如何设置 Sencha Touch List 对象中的行高 我使用 HTML 来格式化行 多行行会变得更高 但如何设置行高 谢谢 格里 要编辑列表元素的默认高度 有两种方法 使用 SASS 创建您自己的 Sencha 主题 官方 Sench
  • 为 Firestore 创建的每个用户的自定义 UID

    请注意 这个问题与问题相同here https stackoverflow com questions 41155905 firebase authentication email password how to set users uid
  • 如何从链表中删除节点?

    将整数添加到列表中工作正常 但删除和打印时出现问题 我对调试器还不友好 但我发现节点指针 first 有错误 它的值为 17891602 我不知道发生了什么事 include
  • 如何在 Flutter 中制作可复制的 Text Widget?

    当长标签打开时Text widget https docs flutter io flutter widgets Text class html 出现一个带有 复制 的工具提示 单击 复制 时 文本内容应复制到系统剪贴板 以下将在长按时复制
  • 如何使用 Dart 设置日期格式?

    我有一个实例DateTime我想将其格式化为字符串 我怎么做 我想将日期转换为字符串 例如 2013 04 20 您可以使用intl https www dartdocs org documentation intl latest intl
  • 将 TextField 下划线颜色更改为渐变

    我可以更改轮廓颜色TextField s使用以下代码将颜色更改为纯色 TextField decoration InputDecoration focusedBorder UnderlineInputBorder borderSide Bo
  • 数据框中按行相关

    我正在尝试计算大型数据帧的所有行之间的相关性 到目前为止已经提出了一个有效的简单 for 循环 例如 name lt c a b c d col1 lt c 43 78 43 84 37 92 31 72 col2 lt c 43 80 4
  • 挑战:优化取消列出[简单]

    因为 SO 最近有点慢 所以我发布了一个简单的问题 如果大鱼们能在这场比赛中留在替补席上并给新秀们一个回应的机会 我将不胜感激 有时我们的对象具有大量的大列表元素 向量 您如何将这个对象 取消列出 到单个向量中 证明你的方法比unlist
  • 将非常大的Python列表输出保存到mysql表中

    我想将 python 生成的列表的输出保存在 mysql 数据库的表中 该表如下所示 mysql 中的 myapc8 表 https i stack imgur com 4B4Hz png这是Python代码 在此输入图像描述 https
  • 添加到列表时有没有办法避免循环?

    我想知道这样的代码 List
  • Firebase Web 与 iOS 和 Android 版本的 React Native 项目

    我是应用程序开发新手 这让我很困惑 我有一个用react native 创建的项目 我希望它可用于android 和iOS 我看过一些关于如何为 React Native 后端创建 Firebase 数据库的教程 其中一些在构建应用程序时选
  • 在 Firestore 文本字段中存储文本文件并删除换行符

    我正在尝试将 CSV 文件存储在 Cloud Firestore 内的文本字段中 然而 Firestore 正在删除所有换行符并将整个 CSV 文件存储为一行 这Firestore 数据类型文档 https firebase google

随机推荐

  • 隐式方法组转换陷阱

    我想知道为什么给定代码的输出 在 LinqPad 中执行 void Main Compare1 Action Main Dump Compare2 Main Dump bool Compare1 Delegate x return x Ac
  • 泛型与接口的实际优势

    在这种情况下 使用泛型与接口的实际优势是什么 void MyMethod IFoo f void MyMethod
  • 推送通知需要很长时间才能到达

    我在适用于 iOS 和 Android 的 Adob e Air 应用程序中遇到推送通知的奇怪问题 我正在使用 Milkman Games 的 Easy Push ANE 以及 One Signal 服务 问题是通知确实会到达 但有时 随机
  • 如何在 couchdb 视图中调用另一个视图?

    我刚刚读完 couchdb 权威指南 一书 并开始摆弄设计文档 然而有一件事我不明白 到目前为止我看到的所有例子都有些线性 Example id 1 rev name first something blue child 2 id 2 re
  • 如何获取 Android 中临时文件的文件大小?

    如果我使用 openFileOutput 创建并写入临时文件 写入完成后如何获取文件大小 我希望这可以帮助你 File file new File selectedPath int file size Integer parseInt St
  • C++ 中的单例和抽象基类

    最近我遇到了关于实现 Singleton 但涉及抽象基类的问题 假设我们有这样的类层次结构 class IFoo it s ABC class Foo public IFoo 我们的单例类定义如下 template
  • 在 sed 命令和范围地址中使用不同的分隔符

    我在 shell 脚本中使用 sed 来编辑文件系统路径名 假设我想替换 foo bar with baz qux 然而 sed 的s 命令使用正斜杠 作为分隔符 如果我这样做 我会看到发出一条错误消息 例如 sed s foo bar b
  • Android LayerDrawable.setDrawableByLayerId 不适用于 HTC Sensation(和其他?)

    我正在使用 LayerDrawable 在底层图像 索引 0 上构建一系列热点 索引 1 热点是根据用户界面交互添加的 并且它们的位置是动态的 因此我以编程方式完成所有这些操作 而不是使用 XML 作为进一步 可能不相关 的细节 我使用 F
  • linkedin js 如何是有效的 javascript

    LinkedIn Javascript 集成是通过以下方式完成的 我不明白 这怎么是一个有效的javascript 为什么 api key 没有被引用 脚本标签的主体带有src永远不会被执行 但是 加载的脚本可以像访问任何其他元素的内容一样
  • 从流程图中获取数据系列的颜色

    在看到 stackoverflow 用户页面上很酷的新 声誉 选项卡后 我受到启发 开始尝试使用 Flot 图表库 我有一个包含数百个系列的折线图 在任何给定时间 这些系列中只有几个是可见的 我的数据系列分为几个 类别 我根据该类别分配数字
  • 迁移大型 Core Data 数据库崩溃

    我有一个将产品存储在核心数据文件中的应用程序 这些产品包括作为 可转换 数据的图像 现在我尝试使用轻量级迁移添加一些属性 当我使用一个小型数据库对其进行测试时 它运行良好 但当我使用一个接近 500 MB 的大型数据库时 应用程序通常会因内
  • 我们如何将数据从一个打开的表单传递到另一个打开的表单?

    winform中如何将数据从一个窗体传递到另一个打开的窗体 在 Windows 应用程序中 一个窗体打开另一个窗体 当我在父表单中输入一些数据时 这些数据将立即反映在另一个子表单中 这将如何发生 取决于你想要多花哨 最简单的方法就是直接调用
  • Kerberos 缓存票证

    我使用的是 Windows 7 64 位 我创建了一个简单的应用程序来对实现 PrivilegedAction 的类的 run 方法中的文件进行计数 以下是我的 jaas conf 文件 CountFiles com sun securit
  • 如何使用 django Rest 框架保存多对多字段对象

    我有博客 发布 标签三个模型 在博客模型中 我将字段 postedin 作为发布模型的外键 将 标签 作为标签模型的许多字段 模型 py class Posted models Model name models CharField Pos
  • 回显 unicode 字符

    我想通过运行bat 文件在cmd 中回显unicode 字符 我准备了一个简短的脚本 echo off SET message G p3 echo message pause 我怎样才能做到这一点 是否可以直接将这封信放入代码中 这样做 两
  • 避免集合已修改错误

    Issue 我有以下代码 foreach var ItemA in GenericListInstanceB ItemA MethodThatCouldRemoveAnyItemInGenericListInstanceB 显然我得到一个错
  • 尝试在空对象引用上调用虚拟方法“java.lang.String org.jsoup.nodes.Element.ownText()”

    我正在使用下面的代码来获取版本名称 from 应用商店通过使用 jsoup 我正在获取详细信息 但它引发了一些异常 我的代码是 public class ForceUpdateAsync extends AsyncTask
  • 将对象直接存储到 ValueStack/ActionContext 的目的是什么?

    根据我的研究 我看到了诸如
  • schema.ini 文件不适用于 MS Access

    我有一堆 csv 文件 我通过 VBA 将它们导入到 Access 中的表中 我在与导入的 csv 文件相同的目录中还有一个 schema ini 文件 尽管在 ini 文件中字段被指定为双精度类型 但它们在 Access 中会转换为文本类
  • 我想将对象列表添加到 firestore 文档中,-flutter

    我想将对象列表添加到 firestore 文档 我定义了产品数据模型 我还有类别数据模型 我想将类别列表添加到 firestore 中的产品文档中 我将类别添加到临时列表 然后将值放入product categories 产品 类别 类别t