Save data from Firestore Flutter

Viewed 27

I want to get some data from 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:

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

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

I want to save the stock and the id for each product. How can I do this?

1 Answers

So the products are already 'saved' on Firestore, however if you want to save them to local storage try this

...
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

Related