Home > Software engineering >  How to update and delete a data in a list according to it's document id - flutter, firebase 202
How to update and delete a data in a list according to it's document id - flutter, firebase 202

Time:10-09

I am trying to delete and update a list of details in flutter. For that i used doc('document_id') which was given as a solution in another stackoverflow question. I tried some another solutions given in stacker flow too. But nothing fork for me. But if I give a specific documentID I am able to delete that. Also how can I pass the selected data to update page too.

class addressProfile extends StatefulWidget {
const addressProfile({Key? key}) : super(key: key);

@override
_addressProfileState createState() => _addressProfileState();
}

class _addressProfileState extends State<addressProfile> {
  var Default = 'unDefault';

delete() async {
try {
  FirebaseFirestore.instance
      .collection("address")
      .doc('document_id')
      .delete();
} catch (e) {
  print(e);
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
  backgroundColor: Colors.grey.shade100,
  appBar: AppBar(
    centerTitle: true,
    backgroundColor: Theme.of(context).scaffoldBackgroundColor,
    title: Text(
      'My Addresses',
      style: TextStyle(color: Colors.black),
    ),
    leading: IconButton(
      icon: Icon(
        Icons.arrow_back_ios,
        color: Colors.black,
      ),
      onPressed: () {
        Navigator.of(context).pushNamed('/profilePage');
      },
    ),
  ),
  body: ListView(
    padding: EdgeInsets.all(16),
    children: [
      StreamBuilder<QuerySnapshot>(
          stream:
              FirebaseFirestore.instance.collection("address").snapshots(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return Expanded(
                child: SizedBox(
                  height: 700,
                  child: ListView.builder(
                    itemCount: snapshot.data!.docs.length,
                    itemBuilder: (context, index) {
                      QueryDocumentSnapshot x = snapshot.data!.docs[index];
                      return Container(
                        child: Card(
                          child: Padding(
                            padding: EdgeInsets.all(12),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Row(
                                  children: [
                                    Text(x['firstName']),
                                    Text(' '),
                                    Text(x['lastName']),
                                  ],
                                ),
                                Text(""),
                                Row(
                                  children: [
                                    Text(x['primaryPhone']),
                                    Text(" / "),
                                    Text(x['secondaryPhone']),
                                  ],
                                ),
                                Text(''),
                                Row(
                                  children: [
                                    Text(x['address1']),
                                    Text(', '),
                                    Text(x['address2']),
                                    Text(', '),
                                    Text(x['city']),
                                    Text(', '),
                                    Text(x['region']),
                                  ],
                                ),
                                Divider(
                                  color: Colors.black,
                                ),
                                Row(
                                  children: [
                                    Container(
                                      child: Radio(
                                          value: 'default',
                                          groupValue: Default,
                                          onChanged: (String? val) {
                                            setState(() {
                                              if (val != null)
                                                Default = val;
                                            });
                                          }),
                                    ),
                                    Container(
                                      child: Text("Default"),
                                    ),
                                    Container(
                                      padding: EdgeInsets.only(left: 60),
                                      child: Align(
                                        child: ElevatedButton.icon(
                                          onPressed: () {
                                            if (snapshot.data!.docs.length >
                                                1) {
                                              delete();
                                              Fluttertoast.showToast(
                                                msg:
                                                    "Address deleted successfully",
                                                toastLength:
                                                    Toast.LENGTH_SHORT,
                                                gravity:
                                                    ToastGravity.BOTTOM,
                                                textColor: Colors.black,
                                                backgroundColor:
                                                    Colors.green.shade400,
                                              );
                                            } else {
                                              Fluttertoast.showToast(
                                                msg:
                                                    "Main address cannot be deleted",
                                                toastLength:
                                                    Toast.LENGTH_SHORT,
                                                gravity:
                                                    ToastGravity.BOTTOM,
                                                textColor: Colors.black,
                                                backgroundColor:
                                                    Colors.green.shade400,
                                              );
                                            }
                                          },
                                          label: Text('Delete'),
                                          style: ElevatedButton.styleFrom(
                                              fixedSize: Size(90, 20),
                                              primary: Colors.red.shade500,
                                              padding: EdgeInsets.symmetric(
                                                horizontal: 5,
                                              ),
                                              shape: RoundedRectangleBorder(
                                                  borderRadius:
                                                      BorderRadius.circular(
                                                          10))),
                                          icon: Icon(
                                              Icons.delete_outline_sharp),
                                        ),
                                      ),
                                    ),
                                    Container(
                                      padding: EdgeInsets.only(left: 14),
                                      child: Align(
                                        child: ElevatedButton.icon(
                                          onPressed: () {
                                            Navigator.push(
                                              context,
                                              MaterialPageRoute(
                                                builder: (builder) =>
                                                    updateAddress(),
                                              ),
                                            );
                                          },
                                          label: Text('Update'),
                                          style: ElevatedButton.styleFrom(
                                              fixedSize: Size(90, 20),
                                              primary:
                                                  Colors.green.shade500,
                                              padding: EdgeInsets.symmetric(
                                                horizontal: 5,
                                              ),
                                              shape: RoundedRectangleBorder(
                                                  borderRadius:
                                                      BorderRadius.circular(
                                                          10))),
                                          icon: Icon(Icons.edit),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        ),
                      );
                    },
                  ),
                ),
              );
            } else {
              return Center(
                child: CircularProgressIndicator(),
              );
            }
          }),
      Align(
        alignment: AlignmentDirectional.bottomCenter,
        child: ElevatedButton(
          onPressed: () {
            Navigator.of(context).pushNamed('/addNewAddress');
          },
          child: Text(
            "Add New Address",
            style: TextStyle(
              fontSize: 15,
              letterSpacing: 2,
              color: Colors.black,
            ),
          ),
          style: ElevatedButton.styleFrom(
              fixedSize: Size(250, 40),
              primary: Colors.green.shade500,
              padding: EdgeInsets.symmetric(
                horizontal: 50,
              ),
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10))),
        ),
      ),
    ],
  ),
);
}
}

This is so far I did. Please help me to continue.

CodePudding user response:

I don't know how you have saved the data. But I got an issue like this and what I did was, I added a variable as "id" to database while saving the data. There is an auto generated id plugin for flutter (nanoid). You can add that and save the data as following.

var id = nanoid(10) //10 is the length of the id. You can give as you wish

create() async {
  try {
    FirebaseFirestore.instance
       .collection("address")
       .doc(id)
       .set({
         "id":id,
         //other inputs 
       });
 } catch (e) {
   print(e);
 }
}

Then you can use that id as a key to update ad delete. For example according to you code to delete you can use like this in the onPress(){} of delete button,

FirebaseFirestore.instance.collection("address").doc(x['id']).delete();

So the data related to id will be deleted. Also better to use proper name rather than "x".

CodePudding user response:

Can you please try this

delete(String docId) async {
    try {
      FirebaseFirestore.instance
          .collection("address")
          .doc(docId)
          .delete();
    } catch (e) {
      print(e);
    }
  }

Your delete function call

delete(snapshot.data!.docs[index].id);

Update document

void update(String docId){
FirebaseFirestore.instance.collection("address").doc(docId) .update({"field1":"fieldValue1","field2":"fieldValue2"});
}

Let me know if you find any issues in comment

  • Related