Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'package:flutter/cupertino.dart';
- import 'package:flutter/material.dart';
- import 'package:matcher/matcher.dart';
- import 'package:cloud_firestore/cloud_firestore.dart';
- import './models/book.dart';
- void main() => runApp(BookApp());
- class BookApp extends StatelessWidget {
- @override
- Widget build(BuildContext context) {
- return MaterialApp(
- debugShowCheckedModeBanner: false,
- title: 'books manager',
- home: BookFirebaseDemo(),
- );
- }
- }
- class BookFirebaseDemo extends StatefulWidget {
- // ======CREATE A CONSTRUCTOR OF BOOKFIREBASEDEMO=========
- BookFirebaseDemo() : super();
- // ======ADD A TITLE TO DB==========(1)======
- final String appTitle = "Book DB";
- @override
- _BookFirebaseDemoState createState() => _BookFirebaseDemoState();
- }
- class _BookFirebaseDemoState extends State<BookFirebaseDemo> {
- // ===========CREATE 2 TEXTEDITING CONTROLLER==========
- TextEditingController _bookNameControler = TextEditingController();
- TextEditingController _bookAuthoControler = TextEditingController();
- // ===========ADD BOOL VARIABLES=======
- bool isEditing = false;
- bool textFieldVisibility = false;
- // =======ADD A COLLECTION NAME , (MATCH TO FIREBASE DB COLLECTION NAME)==============
- String firestoreCollectionName = "Books";
- // =================CREATE A OBJECT FROM BOOK CLASS (BOOK.DART)================
- Book currentBook;
- // ===========CREATE A GETALLBOOKS METHOD (GET ALL DATA FROM BOOK CLASS)===========
- getAllBooks() {
- return Firestore.instance.collection(firestoreCollectionName).snapshots();
- }
- // =======CREATE A METHOD HOW TO ADD DATA TO DOCUMENT==============
- addBook() async {
- Book book = Book(
- bookName: _bookNameControler.text,
- authoName: _bookAuthoControler.text);
- // ==========CREATE TRY CATCH==========
- try {
- Firestore.instance.runTransaction((Transaction transaction) async {
- await Firestore.instance
- .collection(firestoreCollectionName)
- .document()
- .setData(book.toJason());
- });
- } catch (e) {
- print(e.toString());
- }
- }
- // =======CREATE UPDATE BOOK METHOD (CREATE 3 OBJECTS>> BOOK, BOOKNAME, AUTHORNAME)==========
- updateBook(Book book, String bookName, String authoName) {
- try {
- Firestore.instance.runTransaction((transaction) async {
- await transaction.update(book.documentReference,
- {'bookName': bookName, 'authoName': authoName});
- });
- } catch (e) {
- print(e.toString());
- }
- }
- // ========IF CHECK UPDATION, "YES" >> ACTIVATE UPDATE BUTTON & RUN BOOKUPDATE METHOD========
- // =========USE isEditing BOOL VALUE=========
- updateIfEditing() {
- if (isEditing) {
- // ========update========
- updateBook(
- currentBook, _bookNameControler.text, _bookAuthoControler.text);
- // =======AFTER EDIT , RESET THE BOOL VALUE========
- setState(() {
- isEditing = false;
- });
- }
- }
- // ===========DELETE BOOK FUNCTION============
- deleteBook(Book book) {
- Firestore.instance.runTransaction((Transaction transaction) async {
- await transaction.delete(book.documentReference);
- });
- }
- // ===========C R E A T E F R O N T E N D==============
- // =======CREATE A WIDGET ===========
- Widget buildBody(BuildContext context){
- return StreamBuilder<QuerySnapshot>(
- stream: getAllBooks(),
- builder: (context, snapshot) {
- if (snapshot.hasError) {
- return Text("Error ${snapshot.error}");
- }
- if (snapshot.hasData) {
- print("Documents -> ${snapshot.data.documents.length}");
- return buildList(context, snapshot.data.documents);
- }if(!snapshot.hasData || snapshot.data == null) return addBook();
- return CircularProgressIndicator();
- },
- );
- }
- // ===============CREATE A BUILD LIST WIDGET==================
- // ============& CREATE BUILDLIST WIDGET============================
- Widget buildList(BuildContext context, List<DocumentSnapshot> snapshot) {
- return ListView(
- children:
- snapshot.map((data) => listItemBuild(context, data)).toList(),);
- }
- // ============CREATE LISTITEMBUILD WIDGET============
- Widget listItemBuild(BuildContext context, DocumentSnapshot data) {
- final book = Book.fromSnapshot(data);
- return Padding(
- key: ValueKey(book.bookName),
- padding: EdgeInsets.symmetric(vertical: 19.0, horizontal: 2.0),
- child: Container(
- decoration: BoxDecoration(
- border: Border.all(color: Colors.redAccent),
- borderRadius: BorderRadius.circular(5.0),
- ),
- child: SingleChildScrollView(
- child: ListTile(
- title: Column(
- children: <Widget>[
- Row(
- children: <Widget>[
- Icon(
- Icons.book,
- color: Colors.green,
- ),
- Text(book.bookName),
- ],
- ),
- Divider(),
- Row(
- children: <Widget>[
- Icon(
- Icons.person,
- color: Colors.green,
- ),
- Text(book.authoName),
- ],
- ),
- ],
- ),
- trailing: IconButton(
- icon: Icon(
- Icons.delete,
- color: Colors.red,
- ),
- onPressed: () {
- deleteBook(book);
- },
- ),
- // ==========TAP ON THE BOOK DETAIL >>GOES TO UPDATE==========
- onTap: () {
- setUpdateUI(book);
- },
- ),
- ),
- ),
- );
- }
- // =============CREATE SETUPDATEUI>>> TAP THE TILE AFTER SET THE UPDATE BOOK DETAILS==========
- setUpdateUI(Book book) {
- _bookNameControler.text = book.bookName;
- _bookAuthoControler.text = book.authoName;
- setState(() {
- textFieldVisibility = true;
- isEditing = true;
- currentBook = book;
- });
- }
- // ==========CREATE ADD/UPDATE BUTTON AS METHOD============
- // ===========TAP THE TILE, RUN SETUPDATEUI, ADD BUTTON CHANGE TO UPDATE=======
- button() {
- return SizedBox(
- width: double.infinity,
- child: OutlineButton(
- child: Text(isEditing ? "UPDATE" : "ADD"),
- onPressed: () {
- if (isEditing == true) {
- updateIfEditing();
- } else {
- addBook();
- }
- setState(() {
- textFieldVisibility = false;
- });
- },
- ),
- );
- }
- @override
- Widget build(BuildContext context) {
- return SafeArea(
- child: Scaffold(
- // ==========STOP RENDER CRASHING FROM KEYBOARD==========
- resizeToAvoidBottomPadding: false,
- appBar: AppBar(
- // ===========USE APPTITLE VARIABLE=========(1)========
- title: Text(widget.appTitle),
- actions: <Widget>[
- IconButton(
- icon: Icon(Icons.add),
- onPressed: () {
- setState(() {
- textFieldVisibility = !textFieldVisibility;
- });
- }),
- ],
- ),
- body: Container(
- padding: EdgeInsets.all(15.0),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.center,
- mainAxisAlignment: MainAxisAlignment.start,
- children: <Widget>[
- textFieldVisibility
- ? Column(
- crossAxisAlignment: CrossAxisAlignment.center,
- mainAxisAlignment: MainAxisAlignment.start,
- children: <Widget>[
- Column(
- children: <Widget>[
- TextFormField(
- controller: _bookNameControler,
- decoration: InputDecoration(
- labelText: "Book Name",
- hintText: "Enter Book Name",
- ),
- ),
- ],
- ),
- Column(
- children: <Widget>[
- TextFormField(
- controller: _bookAuthoControler,
- decoration: InputDecoration(
- labelText: "Book Author",
- hintText: "Enter Author Name",
- ),
- ),
- ],
- ),
- SizedBox(
- height: 10.0,
- ),
- button()
- ],
- )
- : Container(),
- SizedBox(
- height: 20.0,
- ),
- Text(
- "BOOKS",
- style: TextStyle(
- fontSize: 18.0,
- fontWeight: FontWeight.w800,
- ),
- ),
- SizedBox(
- height: 20.0,
- ),
- Flexible(
- child: buildBody(context),
- ),
- ],
- ),
- ),
- ),
- );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement