Flutter + Firestore how to insert a new document with DocumentReference? - Stack Overflow

admin2025-04-22  2

I'm slowly learning firestore and trying to create a new document that will have two fields as references to other documents. As a string I have no problem storing them, but it would be much more convenient to have them as references. The application when adding closes without any error.

Future<void> add(Products product) async {
    try {
      await _firestoreService.addDocument(
        collectionPath: collection,
        data: product.toMap(),
        documentId: product.name,
      );
    } catch (e) {
      throw Exception('Nie udało się dodać produktu');
    }
  }
 Products _buildProductData() {
    return Products(
      id: '', 
      name: _nameController.text, 
      ean: _eanController.text,
      brand: _selectedBrand!.reference!,
      category: _activeCategory.toList()[0].doc.reference,
    );
  }
import 'package:cloud_firestore/cloud_firestore.dart';

class Products {
  final String id;
  final String name;
  final String ean;
  final DocumentReference brand; 
  final DocumentReference category; 

  Products({
    required this.id,
    required this.name,
    required this.ean,
    required this.brand,
    required this.category,
  });

  factory Products.fromFirestore(DocumentSnapshot doc) {
    final data = doc.data() as Map<String, dynamic>;
    return Products(
      id: doc.id,
      name: data['name'] ?? '',
      ean: data['ean'] ?? '',
      brand: data['brand'],
      category: data['category'],
    );
  }


  Map<String, dynamic> toMap() {
    return {
      'name': name,
      'ean': ean,
      'brand': brand,
      'category': category,
    };
  }
}

I'm slowly learning firestore and trying to create a new document that will have two fields as references to other documents. As a string I have no problem storing them, but it would be much more convenient to have them as references. The application when adding closes without any error.

Future<void> add(Products product) async {
    try {
      await _firestoreService.addDocument(
        collectionPath: collection,
        data: product.toMap(),
        documentId: product.name,
      );
    } catch (e) {
      throw Exception('Nie udało się dodać produktu');
    }
  }
 Products _buildProductData() {
    return Products(
      id: '', 
      name: _nameController.text, 
      ean: _eanController.text,
      brand: _selectedBrand!.reference!,
      category: _activeCategory.toList()[0].doc.reference,
    );
  }
import 'package:cloud_firestore/cloud_firestore.dart';

class Products {
  final String id;
  final String name;
  final String ean;
  final DocumentReference brand; 
  final DocumentReference category; 

  Products({
    required this.id,
    required this.name,
    required this.ean,
    required this.brand,
    required this.category,
  });

  factory Products.fromFirestore(DocumentSnapshot doc) {
    final data = doc.data() as Map<String, dynamic>;
    return Products(
      id: doc.id,
      name: data['name'] ?? '',
      ean: data['ean'] ?? '',
      brand: data['brand'],
      category: data['category'],
    );
  }


  Map<String, dynamic> toMap() {
    return {
      'name': name,
      'ean': ean,
      'brand': brand,
      'category': category,
    };
  }
}
Share Improve this question asked Jan 21 at 14:42 VastuneyVastuney 111 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 0

When creating documents with references (there are sample codes here from GitHub), you must specify a path and ensure you’re handling the references to your toMap() method correctly. From the above snippets you have provided, the reference is not much more than a path.

In the Firebase console UI, below is a sample way of creating a document inside a collection. You’ll see that when you select ‘reference’ as a data type for a field, it will prompt you to specify the document path.

It's important also to validate the data types/methods you’re using, as this might be one of the reasons your app isn't working as intended. Refer to the documentation for the supported data types that Cloud Firestore supports.

To create or add a document, you can use methods like set()—if you want to specify an ID—or add() if you prefer to auto-generate the ID. In some cases, it can be useful to create a document reference with an auto-generated ID and then use the reference later. For this use case, you can call the doc() method. The concept of handling references within Firestore is explained in the Firestore Data Model.

Check these previous Stack Overflow posts (SO1, SO2, SO3) which might help you.

Hope above helps.

转载请注明原文地址:http://anycun.com/QandA/1745303620a90614.html