Felix Kling

Felix Kling

1565253878

Build a CRUD app using Firebase and Flutter (Provider)

Introduction

I am going to spend some time with the project set up to keep things well organized and easy to maintain in the future.

I am intending to make this into an episode-based tutorial so I will add in other parts things like File Upload using Firebase cloud storage and Smart Push Notifications

So, let’s get started.

What we are building

In this tutorial, we will build an app where you can different types of products and show these products in the main view.

Our final app will look like this:

Prerequisites

In order to follow this guide, you need the following:

  • Firebase console (usually linked with the Google account)
  • A Flutter project, e.g. course.productapp ( you need to decide on a project ID for your app using the following pattern <com>.<brand>.<app>. For example, the app would be com.course.productapp.)
  • iOS or ANDROID setup for the Flutter project

Project setup

Before diving into the real coding part, let’s see what are the plugins and assets required in this project.

Firebase console: Project setup

To get started with Firebase, you need to have a Google account. Visit https://firebase.google.com/ and log in with your Google account credentials. You will be logged in to the Firebase console where you need to set up your project. Once logged in you can create a project.

Now, let’s create our Demo project.

In the Firebase console clique add project and chose your project name

ANDROID SetupOnce the project is created, go to the Firebase Console and register your app by clicking Add Firebase to your app Android. Enter your project ID

Download the google-services.json file to the android/app directory

At this point, you can skip all remaining steps in the Firebase console (Flutter does this stuff automatically).Now we need to register our Google services in the Gradle build files under android/build.gradle

buildscript {

   dependencies {

       // …

       classpath ‘com.google.gms:google-services:4.2.0’   // <-- here

   }

}

Next, update your project ID and register the Google services plugin at the bottom of the gradle build file in the app directory.

defaultConfig {

        applicationId “com.course.product” // <-- update this line

        minSdkVersion 21 // <-- you might also need to change this to 21

        // …

    }

// … bottom of file

apply plugin: ‘com.google.gms.google-services’ // <-- add

That’s it. Our android app is ready to go

IOS Setup

The iOS setup is easier and can be completed in one step.

Click add your app to iOS then download the GoogleService-Info.plist file into the ios/Runner/Runnerdirectory from XCode (Make sure to use XCode ).

Plugins

The plugins needed for this project are:

1.cloud_firestore(A Flutter plugin to use the Cloud Firestore API.)

2.firebase_core( Flutter plugin for Firebase Core, enabling connecting to multiple Firebase apps.)

3.provider( A dependency injection system built with widgets for widgets. provider is mostly syntax sugar for InheritedWidget, to make common use-cases straightforward.)

4.get_it(we will use it for dependency injection with provider)

Don’t forget to run flutter packages getAssets

we will need some images for this project which we will use for our product app. (you can find them in under the asset folder in the Github project)

Now . we should be ready to start coding.

Implementation

you can follow the setup project in Github under code_setup branch.

Code Setup

the architecture I am going to use was introduced by Dane Mackier so feel free to check his article Here

Let’s quickly go over the structure. The lib folder is divided into two folders. core and UI. Core contains all the files associated with the logic. UI contains all the files associated with the UI. Core is divided into three folders.

  • Models: Contains all the plain data models
  • Services: Contains the dedicated files that will handle actual business logic
  • ViewModels: Contains the Provider models for each of the Widget views

UI is also divided into three folders.

  • Shared: Contains files used in multiple other UI files
  • Views: Contains the files for the app views
  • Widgets: Contains widget files that are too big to keep in the view files.

we will not be providing a bunch of models and services at the beginning of our app at global context scale. Instead, we’ll inject it using the locator setup in locator.dart

So this is how our project will look

Step 1: Create model class

We’ll go through the app view by view and add what we need.

Our application will need a Product model so under models we will create productModel.dartfile.

This file contains 2 methods :

Product.fromMap(Map snapshot, String id): When data is fetched from Firebase, it is in JSON format. this method allows us to map data from JSON format to our Product format.

toJson() : The toJson() does the opposite which is to map the data back into JSON format before we upload into Firebase.

class Product {

  String id;

  String price;

  String name;

  String img;

  Product({this.id, this.price, this.name,this.img});

  Product.fromMap(Map snapshot,String id) :

        id = id ?? ‘’,

        price = snapshot[‘price’] ?? ‘’,

        name = snapshot[‘name’] ?? ‘’,

        img = snapshot[‘img’] ?? ‘’;

  toJson() {

    return {

      “price”: price,

      “name”: name,

      “img”: img,

    };

  }

}

Step 2: Create Api class

Under our Services directory will perform all the Network work. we will Create an Api class that will request /Read/Delete/ update data from Firebase. That class will contain different methods like fetching data as a stream , getting the document by id, removing/deleting a document …

class Api{

  final Firestore _db = Firestore.instance;

  final String path;

  CollectionReference ref;

  Api( this.path ) {

    ref = _db.collection(path);

  }

  Future<QuerySnapshot> getDataCollection() {

    return ref.getDocuments() ;

  }

  Stream<QuerySnapshot> streamDataCollection() {

    return ref.snapshots() ;

  }

  Future<DocumentSnapshot> getDocumentById(String id) {

    return ref.document(id).get();

  }

  Future<void> removeDocument(String id){

    return ref.document(id).delete();

  }

  Future<DocumentReference> addDocument(Map data) {

    return ref.add(data);

  }

  Future<void> updateDocument(Map data , String id) {

    return ref.document(id).updateData(data) ;

  }

}

Now to hook it up. As mentioned we will not be providing a bunch of models and services at the beginning of our app at global context scale. Instead, we’ll inject it using the locator setup in locator.dart

void setupLocator() {

  locator.registerLazySingleton(() => Api(‘products’));

}

Step 3: Create CRUD Model

The CRUD Model will use the Api class to Handle the different operations. Under viewmodels create the CRUDModel.dart file and add the different functions needed. This model (as well as every other service and model) will be injected using the locator.

class CRUDModel extends ChangeNotifier {

  Api _api = locator<Api>();

  List<Product> products;

  Future<List<Product>> fetchProducts() async {

    var result = await _api.getDataCollection();

    products = result.documents

        .map((doc) => Product.fromMap(doc.data, doc.documentID))

        .toList();

    return products;

  }

  Stream<QuerySnapshot> fetchProductsAsStream() {

    return _api.streamDataCollection();

  }

  Future<Product> getProductById(String id) async {

    var doc = await _api.getDocumentById(id);

    return  Product.fromMap(doc.data, doc.documentID) ;

  }

  Future removeProduct(String id) async{

     await _api.removeDocument(id) ;

     return ;

  }

  Future updateProduct(Product data,String id) async{

    await _api.updateDocument(data.toJson(), id) ;

    return ;

  }

  Future addProduct(Product data) async{

    var result  = await _api.addDocument(data.toJson()) ;

    return ;

  }

}

Now we register it in the locator file.

void setupLocator() {

  locator.registerLazySingleton(() => Api(‘products’));

  locator.registerLazySingleton(() => CRUDModel()) ;

}

that should be all for the logic now we will move to creating our UI and consuming these services.

Step 4: Routing and main configuration

Our app will have 4 screens. To keep things nice and clean we’ll put all the routing in a separate file called router.dart under the UI folder his function receives RouteSettings which contains the name of the route being requested. We’ll also return an error view for any undefined route.

class Router {

  static Route<dynamic> generateRoute(RouteSettings settings) {

    switch (settings.name) {

      case ‘/’ :

        return  MaterialPageRoute(

          builder: (_)=> HomeView()

        );

      case ‘/addProduct’ :

        return MaterialPageRoute(

          builder: (_)=> AddProduct()

        ) ;

      case ‘/productDetails’ :

        return MaterialPageRoute(

            builder: (_)=> ProductDetails()

        ) ;

      default:

        return MaterialPageRoute(

            builder: (_) => Scaffold(

              body: Center(

                child: Text(‘No route defined for ${settings.name}’),

              ),

            ));

    }

  }

}

now under the main file, we will provide the onGenerateRoute property with the static generateRoute function from the Router. You can remove the home property and set the initialRoute to ‘/’ instead. and we will initialize our Provider parameters in the MultiProvider and setup our locator.

void main() {

  setupLocator();

  runApp(MyApp());

}

class MyApp extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return MultiProvider(

      providers: [

        ChangeNotifierProvider(builder: (_) => locator<CRUDModel>()),

      ],

      child: MaterialApp(

        debugShowCheckedModeBanner: false,

        initialRoute: ‘/’,

        title: ‘Product App’,

        theme: ThemeData(),

        onGenerateRoute: Router.generateRoute,

      ),

    );

  }

}

Step 5: Creating Home Screen

In HomeView.dartwe will fetch different products from the collection products and display them in cards. Whenever the list of products is edited or a new product is added the stream will fetch it from Firebase with the help of our provider CRUDModeafter calling it, we will store it into local list variables List<Product> products and then display it.

class _HomeViewState extends State<HomeView> {

  List<Product> products;

  @override

  Widget build(BuildContext context) {

    final productProvider = Provider.of<CRUDModel>(context);

    return Scaffold(

      floatingActionButton: FloatingActionButton(

        onPressed: () {

          Navigator.pushNamed(context, ‘/addProduct’);

        },

        child: Icon(Icons.add),

      ),

      appBar: AppBar(

        title: Center(child: Text(‘Home’)),

      ),

      body: Container(

        child: StreamBuilder(

            stream: productProvider.fetchProductsAsStream(),

            builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {

              if (snapshot.hasData) {

                products = snapshot.data.documents

                    .map((doc) => Product.fromMap(doc.data, doc.documentID))

                    .toList();

                return ListView.builder(

                  itemCount: products.length,

                  itemBuilder: (buildContext, index) =>

                      ProductCard(productDetails: products[index]),

                );

              } else {

                return Text(‘fetching’);

              }

            }),

      ),

    );

    ;

  }

}

Now we will create ProductCard() to display the details of the product:

import ‘package:flutter/material.dart’;

import ‘package:productapp/core/models/productModel.dart’;

import ‘package:productapp/ui/views/productDetails.dart’;

class ProductCard extends StatelessWidget {

  final Product productDetails;

  ProductCard({@required this.productDetails});

  @override

  Widget build(BuildContext context) {

    return GestureDetector(

      onTap: (){

        Navigator.push(context, MaterialPageRoute(builder: (_) => ProductDetails(product: productDetails)));

      },

      child: Padding(

        padding: EdgeInsets.all(8),

        child: Card(

          elevation: 5,

          child: Container(

            height: MediaQuery

                .of(context)

                .size

                .height * 0.45,

            width: MediaQuery

                .of(context)

                .size

                .width * 0.9,

            child: Column(

              children: <Widget>[

                Hero(

                  tag: productDetails.id,

                  child: Image.asset(

                    ‘assets/${productDetails.img}.jpg’,

                    height: MediaQuery

                        .of(context)

                        .size

                        .height *

                        0.35,

                  ),

                ),

                Padding(

                  padding: EdgeInsets.all(16),

                  child: Row(

                    mainAxisAlignment:

                    MainAxisAlignment.spaceBetween,

                    children: <Widget>[

                      Text(

                        productDetails.name,

                        style: TextStyle(

                            fontWeight: FontWeight.w900,

                            fontSize: 22,

                            fontStyle: FontStyle.italic),

                      ),

                      Text(

                        ‘${productDetails.price} $’,

                        style: TextStyle(

                            fontWeight: FontWeight.w900,

                            fontSize: 22,

                            fontStyle: FontStyle.italic,

                            color: Colors.orangeAccent),

                      ),

                    ],

                  ),

                )

              ],

            ),

          ),

        ),

      ),

    );

  }

}

Step 6: Creating Product details and add product Screens

to create a new Product item, we will take the name input and price by the user . We instantiate a new Product object using our Finally we upload to Firebase using our addProduct() function called using the CRUD provider

Scaffold(

  appBar: AppBar(),

  body: Padding(

    padding: EdgeInsets.all(12),

    child: Form(

      key: _formKey,

      child: Column(

        children: <Widget>[

          TextFormField(

            decoration: InputDecoration(

              border: InputBorder.none,

              hintText: ‘Product Title’,

              fillColor: Colors.grey[300],

              filled: true,

            ),

            validator: (value) {

              if (value.isEmpty) {

                return ‘Please enter Product Title’;

              }

            },

              onSaved: (value) => title = value

          ),

          SizedBox(height: 16,),

          TextFormField(

            keyboardType: TextInputType.numberWithOptions(),

            decoration: InputDecoration(

              border: InputBorder.none,

              hintText: ‘Price’,

              fillColor: Colors.grey[300],

              filled: true,

            ),

            validator: (value) {

              if (value.isEmpty) {

                return ‘Please enter The price’;

              }

            },

              onSaved: (value) => price = value

          ),

          DropdownButton<String>(

            value: productType,

            onChanged: (String newValue) {

              setState(() {

                productType = newValue;

              });

            },

            items: <String>[‘Bag’, ‘Computer’, ‘Dress’, ‘Phone’,‘Shoes’]

                .map<DropdownMenuItem<String>>((String value) {

              return DropdownMenuItem<String>(

                value: value,

                child: Text(value),

              );

            }).toList(),

          ),

          RaisedButton(

            splashColor: Colors.red,

            onPressed: () async{

              if (_formKey.currentState.validate()) {

                _formKey.currentState.save();

                await productProvider.addProduct(Product(name: title,price: price,img: productType.toLowerCase()));

                Navigator.pop(context) ;

              }

            },

            child: Text(‘add Product’, style: TextStyle(color: Colors.white)),

            color: Colors.blue,

          )

        ],

      ),

    ),

  ),

);

Now to delete or update a product we will add another screen to check for the product details and from there we can either delete it or change it

class ProductDetails extends StatelessWidget {

  final Product product;

  ProductDetails({@required this.product});

  @override

  Widget build(BuildContext context) {

    final productProvider = Provider.of<CRUDModel>(context);

    return Scaffold(

      appBar: AppBar(

        title: Text(‘Product Details’),

        actions: <Widget>[

         

          IconButton(

            iconSize: 35,

            icon: Icon(Icons.delete_forever),

            onPressed: ()async {

              await productProvider.removeProduct(product.id);

              Navigator.pop(context) ;

            },

          ),

          IconButton(

            iconSize: 35,

            icon: Icon(Icons.edit),

            onPressed: (){

              Navigator.push(context, MaterialPageRoute(builder: (_)=> ModifyProduct(product: product,)));

            },

          )

        ],

      ),

      body: Column(

        mainAxisSize: MainAxisSize.max,

        crossAxisAlignment: CrossAxisAlignment.center,

        children: <Widget>[

          Hero(

            tag: product.id,

            child: Image.asset(

              ‘assets/${product.img}.jpg’,

              height: MediaQuery.of(context).size.height * 0.35,

              width: MediaQuery.of(context).size.width,

            ),

          ),

          SizedBox(

            height: 20,

          ),

          Text(

            product.name,

            style: TextStyle(

                fontWeight: FontWeight.w900,

                fontSize: 22,

                fontStyle: FontStyle.italic),

          ),

          Text(

            ‘${product.price} $’,

            style: TextStyle(

                fontWeight: FontWeight.w900,

                fontSize: 22,

                fontStyle: FontStyle.italic,

                color: Colors.orangeAccent),

          )

        ],

      ),

    );

  }

}

That’s all our app Should Be ready to rock .

Github

Source code available

Final Thoughts

I hope this helped. There are many other things to add on, but this is where you want to start. I am intending to add other functionalities in the future instead of fetching the photos locally we will store it in Firebase storage or adding Firebase ML Kit to recognize the product details and give more information about it

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

Learn Flutter & Dart to Build iOS & Android Apps

Flutter & Dart - The Complete Flutter App Development Course

Dart and Flutter: The Complete Developer’s Guide

Flutter - Advanced Course

Flutter Tutorial - Flight List UI Example In Flutter

Flutter Tutorial for Beginners - Full Tutorial

Using Go Library in Flutter

A Beginners Guide to the Flutter Bottom Sheet

Flutter Course - Full Tutorial for Beginners (Build iOS and Android Apps)

Flutter Tutorial For Beginners - Build Your First Flutter App

Building the SwiftUI Sample App in Flutter

Building Cryptocurrency Pricing App with Flutter


#flutter #firebase #mobile-apps #ios #database

What is GEEK

Buddha Community

Build a CRUD app using Firebase and Flutter (Provider)

Google's Flutter 1.20 stable announced with new features - Navoki

Flutter Google cross-platform UI framework has released a new version 1.20 stable.

Flutter is Google’s UI framework to make apps for Android, iOS, Web, Windows, Mac, Linux, and Fuchsia OS. Since the last 2 years, the flutter Framework has already achieved popularity among mobile developers to develop Android and iOS apps. In the last few releases, Flutter also added the support of making web applications and desktop applications.

Last month they introduced the support of the Linux desktop app that can be distributed through Canonical Snap Store(Snapcraft), this enables the developers to publish there Linux desktop app for their users and publish on Snap Store.  If you want to learn how to Publish Flutter Desktop app in Snap Store that here is the tutorial.

Flutter 1.20 Framework is built on Google’s made Dart programming language that is a cross-platform language providing native performance, new UI widgets, and other more features for the developer usage.

Here are the few key points of this release:

Performance improvements for Flutter and Dart

In this release, they have got multiple performance improvements in the Dart language itself. A new improvement is to reduce the app size in the release versions of the app. Another performance improvement is to reduce junk in the display of app animation by using the warm-up phase.

sksl_warm-up

If your app is junk information during the first run then the Skia Shading Language shader provides for pre-compilation as part of your app’s build. This can speed it up by more than 2x.

Added a better support of mouse cursors for web and desktop flutter app,. Now many widgets will show cursor on top of them or you can specify the type of supported cursor you want.

Autofill for mobile text fields

Autofill was already supported in native applications now its been added to the Flutter SDK. Now prefilled information stored by your OS can be used for autofill in the application. This feature will be available soon on the flutter web.

flutter_autofill

A new widget for interaction

InteractiveViewer is a new widget design for common interactions in your app like pan, zoom drag and drop for resizing the widget. Informations on this you can check more on this API documentation where you can try this widget on the DartPad. In this release, drag-drop has more features added like you can know precisely where the drop happened and get the position.

Updated Material Slider, RangeSlider, TimePicker, and DatePicker

In this new release, there are many pre-existing widgets that were updated to match the latest material guidelines, these updates include better interaction with Slider and RangeSliderDatePicker with support for date range and time picker with the new style.

flutter_DatePicker

New pubspec.yaml format

Other than these widget updates there is some update within the project also like in pubspec.yaml file format. If you are a flutter plugin publisher then your old pubspec.yaml  is no longer supported to publish a plugin as the older format does not specify for which platform plugin you are making. All existing plugin will continue to work with flutter apps but you should make a plugin update as soon as possible.

Preview of embedded Dart DevTools in Visual Studio Code

Visual Studio code flutter extension got an update in this release. You get a preview of new features where you can analyze that Dev tools in your coding workspace. Enable this feature in your vs code by _dart.previewEmbeddedDevTools_setting. Dart DevTools menu you can choose your favorite page embed on your code workspace.

Network tracking

The updated the Dev tools comes with the network page that enables network profiling. You can track the timings and other information like status and content type of your** network calls** within your app. You can also monitor gRPC traffic.

Generate type-safe platform channels for platform interop

Pigeon is a command-line tool that will generate types of safe platform channels without adding additional dependencies. With this instead of manually matching method strings on platform channel and serializing arguments, you can invoke native class and pass nonprimitive data objects by directly calling the Dartmethod.

There is still a long list of updates in the new version of Flutter 1.2 that we cannot cover in this blog. You can get more details you can visit the official site to know more. Also, you can subscribe to the Navoki newsletter to get updates on these features and upcoming new updates and lessons. In upcoming new versions, we might see more new features and improvements.

You can get more free Flutter tutorials you can follow these courses:

#dart #developers #flutter #app developed #dart devtools in visual studio code #firebase local emulator suite in flutter #flutter autofill #flutter date picker #flutter desktop linux app build and publish on snapcraft store #flutter pigeon #flutter range slider #flutter slider #flutter time picker #flutter tutorial #flutter widget #google flutter #linux #navoki #pubspec format #setup flutter desktop on windows

Idrish Dhankot

Idrish Dhankot

1622532470

Hire Dedicated Flutter App Developer USA| Flutter App Developers

Hire Flutter App Developers: WebClues Infotech is a Flutter App Development company. Our Flutter mobile app development team can create cross-platform apps for different industry verticals. Our Flutter developers will help you extend your business’s scope by developing enhanced functionality and a feature-rich app. To provide a rich user experience to your users, hire dedicated Flutter app developers from WebClues Infotech today!

#hire flutter app developers #hire dedicated flutter app developer usa #hire flutter app developer usa #hire dedicated flutter app developer #hire flutter developer #flutter app development company

Best Flutter App Development Company

Are you looking for the best flutter app development company? Then AppClues Infotech is the leading flutter app development company in USA offering the best service worldwide. We focused on developing hybrid mobile apps on Android & iOS and assures our end-user about exceptional and functionally-rich mobile apps.

For more info:
Website: https://www.appcluesinfotech.com/
Email: info@appcluesinfotech.com
Call: +1-978-309-9910

#top flutter app development company in usa #best flutter app development service #best flutter app development company #hire flutter app developers #flutter app development company #expert flutter app development company

Best Flutter App Development Company in USA & India

AppClues Infotech is one of the best flutter app development company in USA & India. Our diverse and experienced team of developers can help you sketch the smartest and quickest solution for your mobile app development projects with the most superior technology.

For more info:
Website: https://www.appcluesinfotech.com/
Email: info@appcluesinfotech.com
Call: +1-978-309-9910

#top flutter app development company in usa #best flutter app development service #best flutter app development company #hire flutter app developers #flutter app development company in usa & india #custom flutter app development service

Best Flutter App Development Services in USA

Looking for the best-in-class Flutter app development services in USA? We at AppClues Infotech offer next-generation mobile app development services using Google’s powerful framework, Flutter.

Our extremely trustworthy and exceptional Flutter app developers help enterprises and businesses to design high-quality native interfaces on cross-platform.

If you have any project ideas, hiring our Flutter app development services helps you get multi-platform applications with seamless animations, appealing UI, and excellent performance.

Flutter Mobile App Development Services
• Flutter Custom App Development
• Flutter App UI/UX Design
• Flutter Widget Development
• Flutter App QA Testing & Maintenance
• Flutter App Updations & Migration
• Flutter for Embedded Devices
• Flutter Development Consultation

For more info:
Website: https://www.appcluesinfotech.com/
Email: info@appcluesinfotech.com
Call: +1-978-309-9910

#top flutter app development company in usa #best flutter app development service in usa #best flutter app development company usa #hire flutter app developers in usa #best flutter app development services in usa #custom flutter app development services in usa