简体   繁体   English

从 Firestore Flutter 保存数据

[英]Save data from Firestore Flutter

I want to get some data from FireStore.我想从 FireStore 获取一些数据。

Here is my code so far:到目前为止,这是我的代码:

void getProducts() async {
    QuerySnapshot querySnapshot = await FirebaseFirestore.instance
        .collection("users")
        .doc(uid)
        .collection('products')
        .get();
    final fields = querySnapshot.docs.map((doc) => doc.data()).toList();
    for (var f in fields) {
      print(f);
    }
  }

The output is the following: output如下:

I/flutter (14637): {name: Milk, stock: 10, id: 1049} I/flutter (14637): {name: Milk, stock: 10, id: 1049}

I/flutter (14637): {name: Bread, stock: 2, id: 51} I/flutter (14637): {name: Bread, stock: 2, id: 51}

I want to save the stock and the id for each product.我想保存每个产品的库存和 id。 How can I do this?我怎样才能做到这一点?

So the products are already 'saved' on Firestore, however if you want to save them to local storage try this所以产品已经“保存”在 Firestore 上,但是如果你想将它们保存到本地存储,试试这个

...
List<Map<String, dynamic>> products = [];
for(var f in fields)
{
   products.add(f);
}

//Create a file in applicationDocumentsDirectory (You will need the path_provider package)
final File file = await savedFile;
file.writeAsStringSync(jsonEncode(products));

static Future<File> get savedFile async {
    final Directory directory = await getApplicationDocumentsDirectory();
    final String path = "${directory.path}/*any_path*/data.json";
    final File file = File(path);
    if(!file.existsSync()) file.createSync(recursive: true);
    return file;
}

path_provider: https://pub.dev/packages/path_provider path_provider: https://pub.dev/packages/path_provider

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM