首页 > 解决方案 > Flutter 的 Cloud Firestore 文档

问题描述

我正在尝试使用 cloud firestore 编写一个带有颤振的应用程序,但在示例页面中我没有看到示例代码的颤振/飞镖选项,我是否遗漏了什么?这是我正在查看的地方https://firebase.google.com/docs/firestore/query-data/get-data 任何帮助都会很棒。谢谢

标签: fluttergoogle-cloud-firestore

解决方案


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

顺便说一句,我已经使用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();
                      },
                    )
                  )
              ),
            ],
          )
        ),
      ),
    );
  }
}


在此处输入图像描述


推荐阅读