skip to Main Content

I have to create a CRUD, which is generated automatically depending on the area we are using.

In the database found in Firebase, all the collections have a document, called 000description, in which it has all the fields we need. In its description it has whether or not it can be empty, data type, yes Whether or not it is unique, if we need it to take the information from another collection and finally what this field contains.

Example:

City {Not empty, String, Not unique, NoForeignkey, Write the city of the client}

Now, for example, if I go to the company section, the code must go to firebase, see how many fields the document 000description has, create a form with the fields and the data type, and put the description of the field in the hint.

If I go to employees, I should do exactly the same, and so on in each of the collections I have.

I have the idea of how to do it, but I haven’t tried anything and I need someone to guide me a little more.

2

Answers


  1. if i am correct you want to read data from firebase and based on that you want to pass values to you form like hints for various fields ?

    if so then tack a look at the following

    Future<void> _fetchDocument() async {
      DocumentSnapshot document = await _firestore.collection('yourCollection').doc('yourDocument_id').get();
      setState(() {
        _document = document;
      });
    }
    
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          title: Text('My Form'),
        ),
        body: _document != null
            ? ListView(
                padding: EdgeInsets.all(16.0),
                children: _document.data().entries.map((entry) {
                  String label = entry.key;
                  dynamic value = entry.value;
                  returnTextFormField(
                    decoration: InputDecoration(
                      hintText: 'Enter $label with $value',
                    )),
                }).toList(),
              )
            : Center(
                child: CircularProgressIndicator(),
              ),
      );
    }
    
    Login or Signup to reply.
  2. One possible solution would be to have a generic class FireCrudRepository which need to be instantiated wherever you need to get access to a specific collection.

    I would recommend having specific implementations, one for each type collection, which could be implemented as Singleton’s.

    /// C.R.U.D. repository.
    abstract class CrudRepository<T> {
      /// Creates an object with the given UID with the provided parameters.
      Future<bool> create(final T instance);
    
      Future<T?> read(final String uid);
    
      /// Updates the object referred by the UID of the provided instance.
      Future<bool> update(final T instance);
    
      /// Deletes the object referred by the given UID.
      Future<bool> delete(final Uid uid);
    }
    
    enum FireCollection {
      cities,
      companies,
    }
    
    extension FireCollectionExt on FireCollection {
      String get path {
        switch (this) {
          case FireCollection.cities:
            return 'cities';
          case FireCollection.companies:
            return 'companies';
        }
      }
    }
    
    class FireCrudRepository<T> implements CrudRepository<T> {
      /// Reference to the collection in the database
      late final CollectionReference<Map<String, dynamic>> _db;
    
      final Map<String, dynamic> Function(T instance) _toJson;
      final T Function(Map<String, dynamic> json) _fromJson;
    
      FireCrudRepository({
        required final FireCollection collection,
        required final Map<String, dynamic> Function(T instance) toJson,
        required final T Function(Map<String, dynamic> json) fromJson,
      })  : this._toJson = toJson,
            this._fromJson = fromJson {
        try {
          // Initialize this Cloud Firestore database.
          this._db = FirebaseFirestore.instance.collection(collection.path);
        } catch (ex, stacktrace) {
          // TODO: Do something with this error.
        }
      }
    
      Future<Description> readDescription() async {
        final docSnapshot = await _db.doc('000description').get();
        if (docSnapshot.exists) {
          // Protection code
          // TODO: Define what to return here
          return null;
        } else if(docSnapshot.data() == null) {
          // TODO: Define what to return here
          return null;
        } else {
          return Description.fromJson(docSnapshot.data()!);
        }
      }
      
      @override
      Future<T?> read(final String uid) async {
        final docSnapshot = await _db.doc(uid).get();
        if (docSnapshot.exists) {
          // Protection code
          // TODO: Define what to return here
          return null;
        } else if(docSnapshot.data() == null) {
          // TODO: Define what to return here
          return null;
        } else {
          return _fromJson(docSnapshot.data()!);
        }
      }
    
      // TODO: implement create, update, delete
    }
    

    Then use it this way:

    final crud = FireCrudRepository<City>(collection: FireCollection.cities, fromJson: City.fromJson, toJson: City.toJson);
    
    final city = crud.read('uid-of-london');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search