Cloud Firestore扑扑文档

时间:2020-03-21 13:21:57

标签: flutter google-cloud-firestore

我正在尝试使用Cloud Firestore用Flutter编写应用程序,但是在示例页面中我没有看到示例代码的flutter / dart选项,我是否缺少某些东西? 这是我正在看的https://firebase.google.com/docs/firestore/query-data/get-data 任何帮助都会很棒。谢谢

2 个答案:

答案 0 :(得分:1)

Firebase文档中确实没有Flutter的示例。我所做的是,我阅读了要尝试了解的有关该主题的Firebase文档,然后使用FlutterFire documentation for Firestore自己构建了相应的Flutter示例。

要导航至Flutter示例,但逐步进行操作(当前)是:

我还根据FlutterFire reference documentation for Firestore中的示例,经常使用Firebase documentation for Firestore查找Flutter的API签名。

答案 1 :(得分:1)

很抱歉,我的回答很晚, 我正在解决自己的项目问题。

通过我使用cloud_firestore插件实现CRUD操作的方式。

SEE_CRUD_OPREATION_OUTPUT_VIDEO

在这里您可以分析我的 完整代码:

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

class CRUDoperation extends StatefulWidget {
  @override
  _CRUDoperationState createState() => _CRUDoperationState();
}

class _CRUDoperationState extends State<CRUDoperation> {
  Firestore firestore = Firestore.instance;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("CRUD"),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.group_add), 
            onPressed: (){
              showDialog(
                context: context,
                child: ShowCustomDialogBox(oprationName: "Add",)
              );
            }
          )
        ],

      ),
      body: Container(
       padding: const EdgeInsets.all(10),
       alignment: Alignment.center,
       child: StreamBuilder<QuerySnapshot>(
         stream: firestore.collection('Employee').snapshots(),     
         builder: (BuildContext context,AsyncSnapshot<QuerySnapshot> snapshot){
          if (snapshot.hasError){
            return new Center(
              child:Text('Error: ${snapshot.error}')
            );
          }
          if(!snapshot.hasData){
            return new Center(
              child:CircularProgressIndicator()
            );
          }
          else{
            var documents = snapshot.data.documents;


            if(documents.length>0){
              return ListView.builder(
                itemCount:documents.length ,
                itemBuilder: (context, index){
                  return Card(
                      child: ListTile(
                        leading: IconButton(
                          icon: Icon(Icons.edit,color: Colors.blue,), 
                          onPressed: (){
                           showDialog(
                             context: context,
                             child: ShowCustomDialogBox(
                              documentSnapshot:documents[index],
                              oprationName: "Edit",
                              )
                            );
                          }
                        ),
                        title: Text(documents[index].data['Name']),
                        subtitle: Text(documents[index].data['Post']),
                        trailing: IconButton(
                          icon: Icon(Icons.delete,color: Colors.red,), 
                          onPressed: (){
                          firestore.collection('Employee').document(documents[index].documentID)
                          .delete().then((onValue){ //delete user
                            print("Deleted successfully");
                          });
                          }
                        ),
                      ),
                    );
                }
              );
            }else{
              return Center(
                child: Text("Add Emlopyee list"),
              );
            }
          }

         }
        ),
      ),

    );
  }
}



//ADD OR EDIT USER DIALOG BOX
class ShowCustomDialogBox extends StatefulWidget {
 final  DocumentSnapshot documentSnapshot;
 final String oprationName;
  ShowCustomDialogBox({ this.documentSnapshot, this.oprationName});

  @override
  State<StatefulWidget> createState() => ShowCustomDialogBoxState();
}


class ShowCustomDialogBoxState extends State<ShowCustomDialogBox>with SingleTickerProviderStateMixin {

  TextEditingController nameController;

  TextEditingController postController ;

  Firestore firestore = Firestore.instance;


  @override
  void initState() {
    super.initState();
   nameController = widget.oprationName == "Edit" ? TextEditingController(text: widget.documentSnapshot.data['Name'])
   : TextEditingController();

    postController = widget.oprationName == "Edit"? TextEditingController(text:widget.documentSnapshot.data['Post'])
    :  TextEditingController();
  }

  launchOpration(){
    if(widget.oprationName == "Edit"){
     editEmployee();
    }else{
      addEmployee();
    }

  }


  addEmployee(){ //Create user
    if(nameController.text.isNotEmpty && postController.text.isNotEmpty){
      firestore.collection("Employee").add({
        'Name':nameController.text,
        'Post':postController.text
      })
      .then((doc){
        print("employee added successfully documentID :${doc.documentID}");
        nameController.clear();
        postController.clear();
        Navigator.of(context).pop();
      });
    }
    else{
      print("Please all fields");
    }
  }

  editEmployee(){   //Update User
    firestore.collection('Employee').document(widget.documentSnapshot.documentID).updateData({
     'Name':nameController.text,
      'Post':postController.text
    }).then((onValue){
      print("employee Edited successfully");
        nameController.clear();
        postController.clear();
        Navigator.of(context).pop();
    });
  }



  @override
  void dispose() {
    nameController.dispose();
    postController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Material(
        color: Colors.transparent,
        child: Container(
          margin: EdgeInsets.all(20.0),
            padding: EdgeInsets.all(8.0),
            height: MediaQuery.of(context).size.height/2.5,
            width: MediaQuery.of(context).size.width,
            decoration: ShapeDecoration(
              color: Colors.white,
              shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8.0))),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                SingleChildScrollView(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Text("${widget.oprationName} Employee"),
                       SizedBox(height:10),
                      TextField(
                        controller: nameController,
                        decoration: InputDecoration(
                          hintText: "Enter Name",
                          border: OutlineInputBorder()
                        ),
                      ),
                      SizedBox(height:10),
                      TextField(
                        controller: postController,
                        decoration: InputDecoration(
                          hintText: "Enter Post",
                          border: OutlineInputBorder()
                        ),
                      ),
                    ],
                  ),
                ),
                Padding(
                padding: const EdgeInsets.only(
                  left: 20.0, right: 10.0, top: 0.0,),
                  child:  ButtonTheme(
                    height: 35.0,
                    minWidth: MediaQuery.of(context).size.width/3.5,
                    child: RaisedButton(
                      color: Colors.blue,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(5.0)),
                      splashColor: Colors.white.withAlpha(40),
                      child: Text(
                        widget.oprationName,
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: 13.0),
                      ),
                      onPressed: () {
                        launchOpration();
                      },
                    )
                  )
              ),
            ],
          )
        ),
      ),
    );
  }
}


enter image description here