I am unable to delete in Firebase database with Flutter

Asked

Viewed 267 times

0

I can’t seem to delete a data in Firebase personal. I created a CRUD I’m already connected with Firebase, the project is configured, and I was able to add some data. But I can’t delete it. It’s not working.

Follow my code below

Model class lawyer Dart.

class Advogado {
  String id;
  String nome;
  String email;
  String telefone;
  String endereco;
  String numeroOAB;

  Advogado(
      {this.id,
      this.nome,
      this.email,
      this.telefone,
      this.endereco,
      this.numeroOAB});

  Advogado.fromMap(DocumentSnapshot document) {
    id = document.id;
    nome = document.data()['nome'];
    email = document.data()['email'];
    telefone = document.data()['telefone'];
    endereco = document.data()['endereco'];
    numeroOAB = document.data()['numeroOAB'];
  }

  Map toMap() {
    var map = <String, dynamic>{};
    map['nome'] = nome;
    map['email'] = email;
    map['telefone'] = telefone;
    map['endereco'] = endereco;
    map['numeroOAB'] = numeroOAB;

    return map;
  }

  String documentId() => id;
}

CRUD class dbadvogad.Dart

class DBAdvogado with ChangeNotifier {
  DBAdvogado({this.fromMap, this.collection});

  final Advogado Function(DocumentSnapshot document) fromMap;
  Advogado advogado;

  String collection;

  CollectionReference collectionReference =
      FirebaseFirestore.instance.collection('advogado');

  Future<String> add(Advogado advogado) async {
    var collection = collectionReference;
    var document = await collection.add(advogado.toMap());
    return document.id;
  }

  Future<void> update(Advogado advogado) async {
    var collection = collectionReference;
    await collection.doc(advogado.documentId()).update(advogado.toMap());
  }

  Future<void> delete(String documentId) async {
    var collection = collectionReference;
    await collection.doc(documentId).delete();
  }

  Future<Advogado> getById(String documentId) async {
    var collection = collectionReference;
    var snapshot = await collection.doc(documentId).get();
    return fromMap(snapshot);
  }

  Future<List<Advogado>> getAll() async {
    var collection = collectionReference;
    List<Advogado> list = [];
    var querySnapshot = await collection.get();
    querySnapshot.docs.forEach((element) {
      list.add(fromMap(element));
    });

    return list;
  }

  CollectionReference filter() {
    return collectionReference;
  }

  List<Advogado> fromSnapshotToAdvogadoList(
      List<DocumentSnapshot> documentList) {
    List<Advogado> list = [];
    documentList.forEach((element) {
      list.add(fromMap(element));
    });
    return list;
  }
}

List that will appear the data to remove or edit

lawyer.

class ListaAdvogado extends StatelessWidget {

@override
  Widget build(BuildContext context) {
    var snapshots =
        FirebaseFirestore.instance.collection('advogado').snapshots();

    Advogado advogado = Advogado();
    DBAdvogado advogados = DBAdvogado();
    String documentId;

    return Scaffold(
      appBar: AppBar(
        title: Text('Lista de Advogados'),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.add),
            onPressed: () {
              Navigator.of(context).pushNamed(
                RotasApp.FORM_ADVOGADO,
              );
            },
          ),
        ],
      ),
      body: StreamBuilder(
        stream: snapshots,
        builder: (
          BuildContext context,
          AsyncSnapshot<QuerySnapshot> snapshot,
        ) {
          if (snapshot.hasError) {
            return Center(child: Text('Erro: ${snapshot.error}'));
          }

          if (snapshot.connectionState == ConnectionState.waiting) {
            return Center(child: CircularProgressIndicator());
          }

          if (snapshot.data.docs.length == 0) {
            return Center(child: Text('Nenhuma tarefa ainda'));
          }

          return ListView.builder(
              itemCount: snapshot.data.docs.length,
              itemBuilder: (ctx, i) {
                var lista = snapshot.data.docs[i].data();
                return ListTile(
                  leading: CircleAvatar(child: Icon(Icons.person)),
                  title: Text(lista['nome']),
                  subtitle: Text(lista['email']),
                  trailing: Container(
                    width: 100,
                    child: Row(
                      children: <Widget>[
                        IconButton(
                          icon: Icon(Icons.edit),
                          color: Colors.green,
                          onPressed: () {
                            Navigator.of(context).pushNamed(
                              RotasApp.FORM_ADVOGADO,
                              arguments: advogado,
                              //advogado
                            );
                          },
                        ),
                        IconButton(
                          icon: Icon(Icons.delete),
                          color: Colors.red,
                          onPressed: () {
                            showDialog(
                              context: context,
                              builder: (ctx) => AlertDialog(
                                title: Text('Excluir Advogado'),
                                content: Text('Tem certeza???'),
                                actions: <Widget>[
                                  FlatButton(
                                    child: Text('Não'),
                                    onPressed: () =>
                                        Navigator.of(context).pop(false),
                                  ),
                                  FlatButton(
                                    child: Text('Sim'),
                                    onPressed: () =>
                                        Navigator.of(context).pop(true),
                                  ),
                                ],
                              ),
                            ).then((confirmed) async {
                              if (confirmed) {
                                await advogados.delete(documentId);                                  }
                            });
                          },
                        ),
                      ],
                    ),
                  ),
                );
              });
        },
      ),
    );
  }
}

1 answer

1


You are switching to delete one documentId blank, because at no point are you feeding this property...

Here at this point:

await advogados.delete(documentId);

Change to:

If you have the firestore package in the latest version

await advogados.delete(snapshot.data.docs[i].id);

If you have the firestore package in an old version

await advogados.delete(snapshot.data.docs[i].documentId);

  • I also imagined that the id was empty. In my CRUD and model code the id is created automatically? I’m still learning flutter and I’m having these difficulties. I had this question about deleting a record in firebase by id. I’ll change my code with this delete and see if it works

  • @Danieldev entering an item in your firestore table, if a document ID is not provided, an automatic is generated. When loading your model through some item received from the bank the ID is already loaded through its method fromMap -> id = document.id;

  • Hello, so I don’t have to ask another question. Could you tell me if for me to update the icon.Edit with onpressed calling {Rotasapp.FORM_ADVOGADO, Arguments: lawyer} I should only use lawyers.update(lawyer)? It’s not working out. Then in onpressed when clicking the edit button I wanted it to return to the form to edit the information and already filled with the data that was added by the user only being necessary to edit

  • @Danieldev advise you to study a little more about, you have created some properties and are not feeding the same... On the edit button you are passing the variable advogado without first feeding her... In editing you would have to pass the Arguments sort of like this arguments: Advogado.fromMap(snapshot.data.docs[i]) .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.