Flutter / Firebase-在文件ID未知的情况下如何执行删除文件功能?

时间:2020-06-09 10:49:44

标签: firebase flutter dart google-cloud-firestore

我是不熟悉和开发应用程序的新手,在该应用程序中我正在使用ListView的数据显示数据。其中有一个删除的IconButton。我希望删除选定的ListTile数据。它以列表的形式显示数据,但不删除。 添加完deleteData()方法之后。它显示以下错误:

'package:flutter / src / rendering / silver_multi_box_adaptor.dart':失败 断言:第263行pos 16:'child == null || indexOf(child)> index' :不正确。

我们非常感谢您的帮助。到目前为止,这是我所做的:

class OrderRequestModel extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: UserOrderRequestModel(),
      theme: new ThemeData(
        primarySwatch: Colors.red,
      ),
    );
  }
}

class UserOrderRequestModel extends StatefulWidget {
  @override
  _UserOrderRequestModelState createState() {
    return _UserOrderRequestModelState();
  }
}

class _UserOrderRequestModelState extends State<UserOrderRequestModel> {
  deleteData(docId) {
    Firestore.instance
        .collection('order_tbl')
        .document(docId)
        .delete()
        .catchError((e) {
      print(e);
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _buildBody(context),
    );
  }
  Stream<QuerySnapshot> getData() async*{
    FirebaseUser firebaseUser = await FirebaseAuth.instance.currentUser();
    yield* Firestore.instance.collection('order_tbl').orderBy('timestamp', descending: true).snapshots();
  }

  Widget _buildBody(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: getData(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) return LinearProgressIndicator();
        return _buildList(context, snapshot.data.documents);
      },
    );
  }

  Widget _buildList(BuildContext context, List<DocumentSnapshot> snapshot) {
    return ListView(
      padding: const EdgeInsets.only(top: 5.0),
      children: snapshot.map((data) => _buildListItem(context, data)).toList(),
    );
  }

  Widget _buildListItem(BuildContext context, DocumentSnapshot data) {
    final record = Record.fromSnapshot(data);
    String _string =getTimeDifferenceFromNow(record.timestamp.toDate());
    return Padding(
      key: ValueKey(record.animal),
      padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
      child: Container(
          decoration: BoxDecoration(
            border: Border.all(color: Colors.grey),
            borderRadius: BorderRadius.circular(5.0),
          ),
          child: new ListTile(
            title: new Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                new Text(
                  "${record.quantity} kg ${record.animal} - ${record.mobile}",
                  style: new TextStyle(fontWeight: FontWeight.bold, color: Colors.black),
                ),
                new Text(
                  _string,
                  style: new TextStyle(color: Colors.grey, fontSize: 12.0),
                ),
              ],
            ),
            trailing: IconButton(
              icon: Icon(Icons.delete_forever),
              onPressed: () => deleteData(data.documentID),
            ),

            subtitle: new Container(
              padding: const EdgeInsets.only(top: 5.0),
              child: new Text(
                record.address,
                style: new TextStyle(color: Colors.red, fontSize: 12.0,),
              ),
            ),
          ),
      ),
    );
  }
}

2 个答案:

答案 0 :(得分:2)

也许这应该起作用,我已将您的代码更改为我的一个有效的代码。

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

class MyDeletingApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Google SignIn',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.red,
      ),
      home: DeleteDataFromFireStore(),
    );
  }
}
class DeleteDataFromFireStore extends StatelessWidget {
  final db = Firestore.instance;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Delete Data from Firestore")),
      body: ListView(
        padding: EdgeInsets.all(12.0),
        children: <Widget>[
          StreamBuilder<QuerySnapshot>(
              stream: db.collection('order_tbl').snapshots(),
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  return Column(
                    children: snapshot.data.documents.map((doc) {
                      return Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 5.0, vertical: 8.0),
                        child: Container(
                          decoration: BoxDecoration(
                            border: Border.all(color: Colors.grey),
                            borderRadius: BorderRadius.circular(5.0),
                        ),
                          child: ListTile(
                            onTap:() async { await db.collection('order_tbl').document(doc.documentID).delete();},
                            onLongPress:() async { await db.collection('order_tbl').document(doc.documentID).delete();},
                            title: new Row(
                              mainAxisSize: MainAxisSize.max,
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: <Widget>[
                                Text(
                                  "${doc.data['quantity']} kg ${doc.data['animal']} - ${doc.data['mobile']}",
                                  style: new TextStyle(fontWeight: FontWeight.bold, color: Colors.black),
                                ),
//                                Text(
//                                  "${doc.data['quantity']}",
//                                  style: new TextStyle(color: Colors.grey),
//                                ),
                              ],
                            ),
                            subtitle: new Container(
                              padding: const EdgeInsets.only(top: 5.0),
                              child: new Text("${doc.data['user']} - ${doc.data['address']} ",
                                style: new TextStyle(color: Colors.red, fontSize: 12.0,),
                              ),
                            ),
                            trailing: IconButton(
                              icon: Icon(Icons.verified_user),
                              onPressed: () async {
                                await db.collection('order_tbl').document(doc.documentID).delete();
                              },
                            ),
                          ),
                        ),
                      );
                    }).toList(),
                  );
                } else {
                  return SizedBox();
                }
              }),
        ],
      ),
    );
  }
}

答案 1 :(得分:1)

  • 删除单个文档:

    var collection = FirebaseFirestore.instance.collection('users');
    await collection.doc('document_id').delete();
    
  • 删除部分文档:

    var collection = FirebaseFirestore.instance.collection('users');
    var snapshot = await collection.where('age', isGreaterThan: 20).get();
    for (var doc in snapshot.docs) {
     await doc.reference.delete();
    }
    
  • 删除所有文档:

    var collection = FirebaseFirestore.instance.collection('users');
    var snapshot = await collection.get();
    for (var doc in snapshot.docs) {
      await doc.reference.delete();
    }