Firebase Setup

Using the flutter firebase API, firebase is accessible and supports frameworks like flutter.It is used for authentication,cloud functions,databases and many other funtion in an application. In this article, we’ll discuss how to set up Firebase for Android applications.

Step 1: How to Add new Project

Open Google Firebase . Click On Add Project.

Step 1

Step 2: Providing Project Name

Enter Your Project Name

Step 2

Step 3: Adding Android App

Click On Android Icon To Add Android App

Step 3

Step 4: Adding Packages

Add your package name , your package name is generally the Application Id in your app level build.gradle file. click on Register app button.

Step 4

defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId “com.coderaspire.ecomm”
minSdkVersion 19
targetSdkVersion flutter.targetSdkVersion
versionCode 2
versionName flutterVersionName
multiDexEnabled true
}

Step 5:

Download google-services.json file and move to android /app/ directory . click on next button.

Step 5

Step 6:

Copy all the required dependencies and add in project level build.gradle file . click next to continue.

Step 6

Copy all the required dependencies and add in project level build.gradle file . Click on next to continue.

Flutter Firebase Authentication

Firebase authentication offers ready-made UI, an easy-to-use SDK, and backend services for user authentication within the app.Firebase Authentication provides backend infrastructure for authenticating users as well as for auto login and email verification.
It supports password, phone, social login, and other methods of authentication.

Add required firebase package in pubspec.yaml file
Import Package And Initialize Firebase Instance In Main Method.

main.dart

import 'package:ecommerce/pages/admin/adminHome.dart';
import 'package:ecommerce/pages/authWidget.dart';
import 'package:ecommerce/pages/providers.dart';
import 'package:ecommerce/pages/signInPage.dart';
import 'package:firebase_core/firebase_core.dart';

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
      // options: DefaultFirebaseOptions.currentPlatform,
      );
  runApp(const ProviderScope(child: SignInReg()));
}

final counterProvider = StateNotifierProvider((ref) {
  return Counter();
});

class Counter extends StateNotifier<int> {
  Counter() : super(0);
  void increment() => state++;
}

class SignInReg extends ConsumerWidget {
  const SignInReg({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    //final count = ref.watch(counterProvider);
    return MaterialApp(
        title: 'E-Comm',
        theme: ThemeData(
            //primarySwatch: Colors.orange,
            colorScheme: ColorScheme.fromSeed(
                seedColor: Colors.orange, primary: Colors.orange)),
        home: Authwidget(
          nonSignedInBuilder: (BuildContext context) {
            return const SignInPage();
            // return const Scaffold(
            //   body: Center(
            //     child: Text("not signed in "),
            //   ),
            // );
          },
          signedInBuilder: (BuildContext context) {
            return Scaffold(
              body: Center(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    const Text("signed in "),
                    ElevatedButton(
                        onPressed: () {
                          ref.read(firebaseAuthProvider).signOut();
                        },
                        child: const Text("Sign out"))
                  ],
                ),
              ),
            );
          },
          adminSignedInBuilder: (BuildContext context) {
            return Adminhome();
          },
        )

        // Scaffold(
        //   floatingActionButton: FloatingActionButton(
        //     onPressed: () {
        //       ref.read(counterProvider.notifier).increment();
        //     },
        //     child: const Icon(Icons.add),
        //   ),
        //   body: Center(
        //     child: Text(count.toString()),
        //   ),
        // ),
        );
  }
}

pubspec.yaml

name: ecommerce
description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: "none" # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.16.2 <3.0.0"

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  firebase_auth: ^3.4.1
  firebase_core: ^1.14.0
  firebase_messaging: ^11.4.4
  provider: ^6.0.2
  cloud_firestore: ^3.1.11 # for database
  firebase_storage: ^10.2.10 #for storage
  flutterfire_ui: ^0.4.0 #
  flutter_riverpod: ^1.0.3

dev_dependencies:
  flutter_test:
    sdk: flutter

  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^1.0.0

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:
  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

signInPage.dart

import 'package:flutter/material.dart';
import 'package:flutterfire_ui/auth.dart';

class SignInPage extends StatelessWidget {
  const SignInPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const SignInScreen(providerConfigs: [
      EmailProviderConfiguration(),
    ]);
  }
}

provider.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

final firebaseAuthProvider =
    Provider<FirebaseAuth>((ref) => FirebaseAuth.instance);

final authStateChangesProvider = StreamProvider<User?>((ref) {
  return ref.watch(firebaseAuthProvider).authStateChanges();
});

authwidget.dart

import 'package:ecommerce/pages/providers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class Authwidget extends ConsumerWidget {
  final WidgetBuilder nonSignedInBuilder;
  final WidgetBuilder signedInBuilder;
  final WidgetBuilder adminSignedInBuilder;
  var adminEmail = 'admin@gmail.com';
  Authwidget({
    Key? key,
    required this.signedInBuilder,
    required this.nonSignedInBuilder,
    required this.adminSignedInBuilder,
  }) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final authStateChanges = ref.watch(authStateChangesProvider);
    return authStateChanges.when(
      data: (user) => user != null
          ? user.email == adminEmail
              ? adminSignedInBuilder(context)
              : signedInBuilder(context)
          : nonSignedInBuilder(context),
      loading: () => const Scaffold(
        body: Center(
          child: CircularProgressIndicator(),
        ),
      ),
      error: (_, __) => const Scaffold(
          body: Center(
        child: Text("Something went wrong!"),
      )),
    );
  }
}

adminhome.dart


import 'package:ecommerce/pages/providers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class Adminhome extends ConsumerWidget {
  const Adminhome({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, ref) {
    return Scaffold(
      appBar: AppBar(title: const Text('Admin Home'), actions: [
        IconButton(
          onPressed: () => ref.read(firebaseAuthProvider).signOut(),
          icon: const Icon(Icons.logout),
        )
      ]),
    );
  }
}
4 thoughts on “Flutter Firebase”

Leave a Reply

Your email address will not be published. Required fields are marked *