Implementing Firebase GitHub Authentication in Flutter

Implementing Firebase GitHub Authentication in Flutter

In this article, I’m going to show you how to implement Firebase&nbsp;<strong>GitHub authentication</strong>&nbsp;method properly in Flutter. As you might already know, there are some&nbsp;<a href="https://github.com/flutter/plugins" target="_blank">Flutter plugins</a>&nbsp;that are provided officially by Flutter team. And&nbsp;<a href="https://github.com/flutter/plugins/blob/master/FlutterFire.md" target="_blank"><strong>FlutterFire</strong></a>&nbsp;is a subset of them. I encourage you to go and try FlutterFire plugins sometime if you need quick backend solutions for your small-scale project; but for this article we’re going to need only the&nbsp;<a href="https://pub.dartlang.org/packages/firebase_auth" target="_blank"><strong>firebase_auth</strong></a>&nbsp;plugin. So, let me list all the steps that you need to do in order to implement GitHub authentication in your Flutter app:

In this article, I’m going to show you how to implement Firebase GitHub authentication method properly in Flutter. As you might already know, there are some Flutter plugins that are provided officially by Flutter team. And FlutterFire is a subset of them. I encourage you to go and try FlutterFire plugins sometime if you need quick backend solutions for your small-scale project; but for this article we’re going to need only the firebase_auth plugin. So, let me list all the steps that you need to do in order to implement GitHub authentication in your Flutter app:

Step 0. First of all, I assume that you already downloaded google-services.jsonfile for Android and GoogleServices-Info.plist file for iOS from Firebase dashboard of your app and added them to your project properly.

Step 1. Create an OAuth app on GitHub via this link: https://github.com/settings/applications/new. As “authorization callback URL”, you need to set something like appname://auth. You will be redirected to this URL once you successfully log into GitHub on browser (which is the first step of this authorization method from the user point of view). We’re going to utilize this URL in later steps to set app’s deep link configuration, so that you can be redirected back to the app.

Step 2. Enable GitHub authentication method on your app’s Firebase dashboard. As “client ID” and “client secret”, you need to set what GitHub has provided after creating OAuth app on GitHub in Step 1.

Step 3. Add the following dependencies to your project’s pubspec.yaml file:

dependencies:
  firebase_auth: ^0.8.2
  google_sign_in: ^4.0.1+1
  url_launcher: ^5.0.2
  uni_links: ^0.2.0
  http: ^0.12.0+1
  • google_sign_in is required by the firebase_auth dependency, so we need to add it as well.
  • url_launcher will be used to launch URL on browser.
  • uni_links is to add deep-linking capability to the app.
  • http will be used to send HTTP request.

Why and where we need all these will be much more meaningful in the upcoming steps, so please bear with me.

Step 4. For Android, add the following classpath to project-level build.gradlefile located under /android directory:

dependencies {
  // ...
  classpath 'com.google.gms:google-services:4.2.0'
}

And add the following line to the end of app-level build.gradle file located under /android/app directory:

apply plugin: 'com.google.gms.google-services'

Finally, add the following intent filter to the AndroidManifest.xml file located under /android/app/src/main directory:

<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data
        android:host="auth"
        android:scheme="appname" />
</intent-filter>

Please be aware that scheme and host properties we set here are from Step 1.

Step 5. For iOS, add the following attributes into Info.plist file located under /ios/Runner directory:

<key>CFBundleURLTypes</key>
<array>
   <dict>
        <key>CFBundleTypeRole</key>
        <string>Editor</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string><!-- REVERSED_CLIENT_ID from GoogleServices-Info.plist --></string>
        </array>
   </dict>
   <dict>
        <key>CFBundleTypeRole</key>
        <string>Editor</string>
        <key>CFBundleURLName</key>
        <string>auth</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>foreach</string>
        </array>
    </dict>
</array>

Once again, please be aware that in the first “dict” element of the above array, value of CFBundleURLSchemes attribute is set as the REVERSED_CLIENT_IDwhich you can find in GoogleServices-Info.plist file. Similarly, values of CFBundleURLName and CFBundleURLSchemes attributes in the second “dict” element are from Step 1.

We’ve completed the configuration steps. Now, we are ready to go with coding…

Step 6. Import url_launcher package and launch the GitHub login page on browser as follows:

import 'package:url_launcher/url_launcher.dart';
//...
void onClickGitHubLoginButton() async {
  const String url = "https://github.com/login/oauth/authorize" +
      "?client_id=" + GITHUB_CLIENT_ID +
      "&scope=public_repo%20read:user%20user:email";

if (await canLaunch(url)) {
await launch(
url,
forceSafariVC: false,
forceWebView: false,
);
} else {
print("CANNOT LAUNCH THIS URL!");
}
}

On this page, you need to log in with your GitHub credentials.

Step 7. After successfully logging into GitHub, you will get redirected to the URL appname://auth?code=AUTH_CODE. This redirection will be caught by your app as we’ve set the deep link configuration in Step 4 & 5, and you will be redirected (or asked to be redirected) back to the app afterwards.

At this point, to be able to handle incoming data, or in other words, to parse the URL given above and get the AUTH_CODE value from it, you need to have the following setup in your login page widget code:

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:uni_links/uni_links.dart';

class LoginPage extends StatefulWidget {
@override
_LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<SplashPage> {
StreamSubscription _subs;

// ...

@override
void initState() {
_initDeepLinkListener()
super.initState();
}

@override
void dispose() {
_disposeDeepLinkListener();
super.dispose();
}

// ...

void _initDeepLinkListener() async {
_subs = getLinksStream().listen((String link) {
_checkDeepLink(link);
}, cancelOnError: true);
}

void _checkDeepLink(String link) {
if (link != null) {
String code = link.substring(link.indexOf(RegExp('code=')) + 5);
loginWithGitHub(code)
.then((firebaseUser) {
print("LOGGED IN AS: " + firebaseUser.displayName);
}).catchError((e) {
print("LOGIN ERROR: " + e.toString());
});
}
}

void _disposeDeepLinkListener() {
if (_subs != null) {
_subs.cancel();
_subs = null;
}
}
}

In this code, basically we are listening for deep links incoming to the app.

As stated, after a successful GitHub login, you have the “code” in your hands. Now, you need to use it to get access token from GitHub, which afterwards will be used to log into Firebase. Remember that this is our eventual goal.

Step 8. Implement the loginWithGitHub(…) method highlighted in the code above as follows:

import 'package:firebase_auth/firebase_auth.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
// ...
Future<FirebaseUser> loginWithGitHub(String code) async {
//ACCESS TOKEN REQUEST
final response = await http.post(
"https://github.com/login/oauth/access_token",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: jsonEncode(GitHubLoginRequest(
clientId: GITHUB_CLIENT_ID,
clientSecret: GITHUB_CLIENT_SECRET,
code: code,
)),
);

GitHubLoginResponse loginResponse =
GitHubLoginResponse.fromJson(json.decode(response.body));

//FIREBASE STUFF
final AuthCredential credential = GithubAuthProvider.getCredential(
token: loginResponse.accessToken,
);

final FirebaseUser user = await FirebaseAuth.instance.signInWithCredential(credential);
return user;
}
// ...
//GITHUB REQUEST-RESPONSE MODELS
class GitHubLoginRequest {
String clientId;
String clientSecret;
String code;

GitHubLoginRequest({this.clientId, this.clientSecret, this.code});

dynamic toJson() => {
"client_id": clientId,
"client_secret": clientSecret,
"code": code,
};
}

class GitHubLoginResponse {
String accessToken;
String tokenType;
String scope;

GitHubLoginResponse({this.accessToken, this.tokenType, this.scope});

factory GitHubLoginResponse.fromJson(Map<String, dynamic> json) =>
GitHubLoginResponse(
accessToken: json["access_token"],
tokenType: json["token_type"],
scope: json["scope"],
);
}

So, what we’re doing here is that first we request for an access token by sending an HTTP POST call (to the address shown in the code) whose request body contains the “code” we’ve got in the previous step, together with app’s GitHub credentials (“client ID” and “client secret”). Then, using the access token we get in the response of this call, we sign into Firebase. If everything goes successfully, you should eventually have FirebaseUser object in your hands.

Well done! You’re now logged into Firebase with your GitHub account.

I wanted to share how I implemented Firebase GitHub authentication in Flutter since I couldn’t find any resource on the net while trying to achieve this for my project. I hope that this article helps you and makes things clearer a bit.

Stay safe and with Flutter…

Originally published on https://medium.com

How to integrate your iOS Flutter App with Firebase on MacOS

How to integrate your iOS Flutter App with Firebase on MacOS

In this tutorial I am going to show you how to connect your Flutter iOS application to the Firebase Platform on a Mac Computer so you can utilize the powerful services provided by the firebase API in your future endeavors…

In this tutorial I am going to show you how to connect your Flutter iOS application to the Firebase Platform on a Mac Computer so you can utilize the powerful services provided by the firebase API in your future endeavors…

Firebase is a mobile app development platform developed by Firebase, Inc. in 2011, and then Acquired by Google in 2014. It provides various features such as Cloud Storage, Authentication and an ML kit, which are essential to developing modern mobile applications. Additionally, it provides services such as Performance Monitoring, Crashlytics and Google Analytics to help you improve the quality of your applications.

1. Readying a Gmail Account and a Flutter Project

In order to utilize services from Firebase and Google Cloud Platform, you will need a Google Account. If you do not have one, simply following the page instructions here to register for one.

This tutorial is going to show you how to connect your existing Flutter application to the Firebase platform. If you are interested in how to create your first Flutter application, I have a tutorial on How to create your first iOS Flutter app on MacOS. By the end of that tutorial, you should have a hello_world application ready in the simulator and understand how to alter the application by modifying the main.dart file.

2. Creating a Firebase Project

In order to integrate your Flutter application with the Firebase Platform, first you have to create a Firebase Project. And here are the steps.

  1. Go to the Firebase Console.

  2. Click on the big Add project button.

  1. Enter your Project name.
  • I used hello-world for this example. Firebase automatically appends a unique ID to your project name — for example, the project I created ended up with the name hello-world-f2206.
  1. You can pick a Cloud Firestore Location.
  • I used hello-world for this example. Firebase automatically appends a unique ID to your project name — for example, the project I created ended up with the name hello-world-f2206.
  1. Accept the Terms and Conditions.

  1. Once you are done, scroll to the bottom and click Create Project.

  • I used hello-world for this example. Firebase automatically appends a unique ID to your project name — for example, the project I created ended up with the name hello-world-f2206.

Firebase will take some time to ready your application. Once done, click on the Continue button to open up the Firebase Project Overview Page.

4. Configure an iOS Application

  1. In your Firebase Project Overview Page, launch the setup wizard for iOS.

  1. Inside the setup wizard, put in the iOS bundle ID. The Register app button should then light up, click on it.
  • I used hello-world for this example. Firebase automatically appends a unique ID to your project name — for example, the project I created ended up with the name hello-world-f2206.

  1. Download the GoogleService-Info.plist configuration file and put it into the iOS Project root folder, then click Next.
  • I used hello-world for this example. Firebase automatically appends a unique ID to your project name — for example, the project I created ended up with the name hello-world-f2206.

  1. Follow the instructions to add the Firebase SDK, then click Next.

  • I used hello-world for this example. Firebase automatically appends a unique ID to your project name — for example, the project I created ended up with the name hello-world-f2206.
  1. Modify the code inside the main AppDelegate as instructed by the setup wizard then click Next. For this example, I used Objective-C, and therefore replaced the contents inside AppDelegate.m with the following code.
#include "AppDelegate.h"
#include "GeneratedPluginRegistrant.h"

@import UIKit;
@import Firebase;

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[FIRApp configure];
return YES;
}

@end

  1. Get back to the root folder and run your app, after a while you should see the setup wizard showing that your app is added to Firebase. Click Continue to the Console to finish the setup.

Congratulations! You have successful added Firebase to your Flutter application. Despite the fact that having both Firebase and Flutter from Google is supper cool, it is actually a good Software Engineering practice to always have a plan B, as well as plan C, D,E, F, and G. In the future I will write another guide on an example application utilizing Firebase, and more on Flutter.

Have fun coding!!!

Appendices:

3.1 Switching to Administrator Account

If you ran into the following message, it means that you need to contact the organization of your Gmail account to grant you access to Google Developers Console.

4.1 Finding iOS Project root folder & Acquiring Bundle ID

  1. Launch Xcode from the Launchpad.

  2. Select “Open another project…” at the bottom of the prompt screen.

  1. Navigate to your Flutter project folder, open the “ios” folder and select “Runner.xcodeproj”. This should automatically open up the project in Xcode.

  1. Select the Runner project on the left, you should now see the Bundle Identifier under Identity.

4.2 Installing CocoaPods and Firebase SDK

In case the instructions inside the setup wizard did not work out, you will have to remove the existing Podfile in order to reinstall them correctly.

  1. CocoaPods is built with Ruby and is installable with the default Ruby available on MacOS. Use the following commands to install it.
sudo gem install cocoapods

  1. Initialize the Podfile with the following command.
pod init

  1. Then, add the following code to the initialized Podfile.
pod 'Firebase/Core'

  1. Once done, save the changes made to the Podfile, and install the Firebase SDK with the following command.
pod install

  1. After the installation, you will likely have to configure the .xcconfig files. First you will have to copy the files from the Pods/Target Support Files/Pods-Runner folder to Flutter folder.

  1. Then you will have to include them into the Debug.xcconfig and Release.xcconfig files inside the Flutter folder.

In Debug.xcconfig:

#include "Pods-Runner.debug.xcconfig"

In Release.xcconfig:

#include "Pods-Runner.profile.xcconfig"
#include "Pods-Runner.release.xcconfig"

Build a CRUD app using Firebase and Flutter (Provider)

Build a CRUD app using Firebase and Flutter (Provider)

In this article, I will be showing how to set up and build a CRUD app using Firebase and a state management package called Provider that was announced by the Flutter team at Google I/O 2019.

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 Grocery Shopping Mobile App

Flutter Grocery Shopping Mobile App

This Flutter grocery app is a pro version that has all features of online grocery purchase for your customers.

FLUTTER GROCERY APP
Are you looking to launch your online grocery shop or any E-Commerce mobile app then this flutter grocery app will help you to build the app in just days? We offer an online grocery software system. The mobile application offers amazing features to build a powerful online ordering system or app for your grocery shop. It enhances online home grocery stuffs ordering experience for your customers with your mobile grocery app. This Flutter grocery app is a fully functional mobile app that has all features of online grocery purchase for your customers. So what are you waiting for? Start your online business with your Mobile app today!

YOu check live demo and feature video at:
https://www.youtube.com/watch?v=Y0bn_3Uu2u0