Deleting Firestore Data in Flutter List View

烈酒焚心 提交于 2021-02-15 07:32:15

问题


I have a regular List View that fetches some data from Firestore, here is the code for it:

body: StreamBuilder(
      stream: FirebaseFirestore.instance.collection('orders').snapshots(),
      builder: (context, snapshot) {
        if (!snapshot.hasData)
          return Center(
            child:
                CircularProgressIndicator(), 
          );
        return ListView.builder(
       
          itemCount: snapshot.data.docs.length,
          itemBuilder: (context, index) {
            DocumentSnapshot ds = snapshot.data.docs[index];
  
            return Text(ds['name']);

Now if I wanted to create a delete button somewhere in it, I would do something like this:

FirebaseFirestore.instance.collection('orders').doc('ID SHOULD BE HERE').delete();

The issue I have is how do I find the document ID of the list tile on here in order to delete it automatically from the database? ID SHOULD BE HERE in the code should be some command to find the id of it like in the screenshot below:


回答1:


DocumentSnapshot contains a property called id which will return the document's given ID for this snapshot. Therefore you can do the following:

itemBuilder: (context, index) {
  DocumentSnapshot ds = snapshot.data.docs[index];
  print(ds.id);
  return Text(ds['name']);



回答2:


By saving the reference id from doc in local model and using the reference id on your required set of operation

I have provide the realtime example of removing the data.

class Employee {
  Employee(this.employeeID, this.employeeName, this.branch, this.designation, this.location,
      this.salary,
      {this.reference});

  double employeeID;

  String employeeName;

  String designation;

  String branch;

  String location;

  double salary;

  DocumentReference reference;

  factory Employee.fromSnapshot(DocumentSnapshot snapshot) {
    Employee newEmployee = Employee.fromJson(snapshot.data());
    newEmployee.reference = snapshot.reference;
    return newEmployee;
  }

  factory Employee.fromJson(Map<String, dynamic> json) =>
      _employeeFromJson(json);

  Map<String, dynamic> toJson() => _employeeToJson(this);

  @override
  String toString() => 'employeeName ${employeeName}';
}

Employee _employeeFromJson(Map<String, dynamic> data) {
  return Employee(
    data['employeeID'],
    data['employeeName'],
    data['branch'],
    data['designation'],
    data['location'],
    data['salary'],
  );
}

Map<String, dynamic> _employeeToJson(Employee instance) {
  return {
    'employeeID' : instance.employeeID,
    'employeeName': instance.employeeName,
    'branch': instance.branch,
    'designation': instance.designation,
    'location': instance.location,
    'salary': instance.salary,
  };
}

Repository

class EmployeeRepository{
  List<Employee> employees = [];

  final CollectionReference collection =
      FirebaseFirestore.instance.collection('employees');

  Stream<QuerySnapshot> getStream() {
    return collection.snapshots();
  }
  
  Future<DocumentReference> add(Employee employee) {
    var documentReference = collection.add(employee.toJson());
    return documentReference;
  }

  update(Employee employee) async {
    collection.doc(employee.reference.id).update(employee.toJson());
  }


  delete(Employee employee) async {
    collection.doc(employee.reference.id).delete();
  }

  fromSnapShot(DocumentSnapshot snapshot) => Employee.fromSnapshot(snapshot);

  Future<void> buildData(AsyncSnapshot snapshot) async {
    if (snapshot.data.documents.length == 0) {
      employees = [];
    }

    employees = await snapshot.data.documents.map<Employee>((doc) {
      return Employee.fromSnapshot(doc);
    }).toList(growable: false);
  }
}

Listview builder

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text('Employees List'),
    ),
    body: Column(children: [
      StreamBuilder<QuerySnapshot>(
          stream: employeeRepository.getStream(),
          builder: (context, snapShot) {
            if (!snapShot.hasData ||
                snapShot.hasError ||
                snapShot.connectionState == ConnectionState.waiting) {
              return Container(
                child: Center(child: CircularProgressIndicator()),
              );
            }
            
              employeeRepository.buildData(snapShot);
              return ListView.builder(
                itemBuilder: (context, index) {
                  final employee = employeeRepository.employees[index];
                  return ListTile(
                    title: Text(employee.employeeName),
                    onLongPress: () {
                      showDialog<AlertDialog>(
                          context: context,
                          builder: (context) {
                            return AlertDialog(
                              actions: [
                                FlatButton(
                                    onPressed: () {},
                                    child: Text('Edit')),
                                FlatButton(
                                    onPressed: () {
                                      setState(() {
                                        employeeRepository
                                            .delete(employee);
                                        Navigator.pop(context);
                                      });
                                    },
                                    child: Text('Delete')),
                              ],
                              content: Text(employee.employeeName),
                            );
                          });
                    },
                  );
                },
              );
          }),
    ]),
  );
}

CRUD Operation in firestore



来源:https://stackoverflow.com/questions/65959381/deleting-firestore-data-in-flutter-list-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!