A comprehensive guide on installing Flutter SDK, setting up a new Flutter project, and integrating Firebase for Android and iOS applications. Step-by-step instructions include Google sign-in setup, required dependencies, and running the app in an emulator

Flutter SDK installation#

Before this install android studio. First you need to install flutter sdk on your system. Refer this

Verify your installation using

Bash
1flutter --version

If it shows you the version without any error. you are good to go with next steps.

Create flutter project#

You can use flutter sdk to create a project. Navigate to your projects folder (where you want to store your flutter project) from terminal. Then use the following command.

Bash
1flutter create firebase-authentication

This will create a folder named firebase-authentication that has our initial setup for our flutter project.

Bash
1code firebase-authentication

Use above command to open our flutter project on Visual Studio Code.

Bash
1flutter run

After opening project in vs code. Use ctrl + ` to open terminal or View -> terminal. And use above command to run our flutter app

Blog image

It will run in an emulator and the UI will be like the image above. Having a counter which increments on button press.

Firebase Setup:#

Navigate to firebase console.

Blog image

1. Click on create project

Blog image

2. Give it a meaning full name and click on continue

Blog image

3. You can keep this as it is and continue

Blog image

4. Select your default account and click on create project.

That's it firebase project got created.

Now we need to add firebase to android and ios apps.

Adding firebase to Android app#

Blog image

1. I updated project name to KUCET. You should still see firebase-authentication. But all you need to do is click that android icon

Blog image

2. Fill in the details and click on continue

Blog image

3. Download google-services.json and store it in android/app/google-services.json

Blog image

4. In android/settings.gradle add 'com.google.gms.google-services' in plugins. Plugins should look like this

Text
1plugins {
2    id "dev.flutter.flutter-plugin-loader" version "1.0.0"
3    id "com.android.application" version "8.1.0" apply false
4    id "org.jetbrains.kotlin.android" version "1.8.22" apply false
5    id 'com.google.gms.google-services' version '4.4.2' apply false
6}

5. In android/app/build.gradle add 'com.google.gms.google-services' in plugins. Plugins should look like this

Text
1plugins {
2    id "com.android.application"
3    id "kotlin-android"
4    // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
5    id "dev.flutter.flutter-gradle-plugin"
6    id 'com.google.gms.google-services'
7}

6. Update minSdk to 23

Text
1defaultConfig {
2        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
3        applicationId = "appId"
4        // You can update the following values to match your application needs.
5        // For more information, see: https://flutter.dev/to/review-gradle-config.
6        minSdk = 23
7        targetSdk = flutter.targetSdkVersion
8        versionCode = flutter.versionCode
9        versionName = flutter.versionName
10    }

Adding firebase to IOS app#

  1. Similar to android, click on ios icon and create in a similar way
  2. Add the downloaded ‘GoogleService-info.plist’ file inside iOS>Runner folder.
Blog image
  1. That's it for IOS setup


Install required dependencies#

Bash
1flutter pub add firebase_auth
2flutter pub add google_sign_in

UI#

JavaScript
1import 'package:firebase_auth/firebase_auth.dart';
2import 'package:flutter/material.dart';
3import 'package:google_sign_in/google_sign_in.dart';
4
5class GoogleSignInScreen extends StatefulWidget {
6  const GoogleSignInScreen({Key? key}) : super(key: key);
7
8  @override
9  State<GoogleSignInScreen> createState() => _GoogleSignInScreenState();
10}
11
12class _GoogleSignInScreenState extends State<GoogleSignInScreen> {
13  ValueNotifier<UserCredential?> userCredential = ValueNotifier(null);
14
15  @override
16  Widget build(BuildContext context) {
17    return Scaffold(
18      backgroundColor: Colors.grey[100],
19      appBar: AppBar(
20        elevation: 0,
21        backgroundColor: Colors.white,
22        title: const Text(
23          'Welcome',
24          style: TextStyle(
25            color: Colors.black87,
26            fontSize: 24,
27            fontWeight: FontWeight.w600,
28          ),
29        ),
30        centerTitle: true,
31      ),
32      body: ValueListenableBuilder(
33        valueListenable: userCredential,
34        builder: (context, value, child) {
35          return AnimatedSwitcher(
36            duration: const Duration(milliseconds: 300),
37            child: userCredential.value == null
38                ? _buildSignInView()
39                : _buildProfileView(),
40          );
41        },
42      ),
43    );
44  }
45
46  Widget _buildSignInView() {
47    return Center(
48      child: Column(
49        mainAxisAlignment: MainAxisAlignment.center,
50        children: [
51          const Text(
52            'Sign in with Google',
53            style: TextStyle(
54              fontSize: 24,
55              fontWeight: FontWeight.bold,
56              color: Colors.black87,
57            ),
58          ),
59          const SizedBox(height: 20),
60          Container(
61            decoration: BoxDecoration(
62              boxShadow: [
63                BoxShadow(
64                  color: Colors.grey.withOpacity(0.2),
65                  spreadRadius: 1,
66                  blurRadius: 10,
67                  offset: const Offset(0, 3),
68                ),
69              ],
70            ),
71            child: ElevatedButton(
72              onPressed: () async {
73                userCredential.value = await signInWithGoogle();
74                if (userCredential.value != null) {
75                  print(userCredential.value?.user?.email);
76                }
77              },
78              style: ElevatedButton.styleFrom(
79                backgroundColor: Colors.white,
80                padding: const EdgeInsets.symmetric(
81                  horizontal: 32,
82                  vertical: 16,
83                ),
84                shape: RoundedRectangleBorder(
85                  borderRadius: BorderRadius.circular(30),
86                ),
87              ),
88              child: Row(
89                mainAxisSize: MainAxisSize.min,
90                children: [
91                  const Icon(
92                    Icons.login,
93                    color: Colors.blue,
94                  ),
95                  const SizedBox(width: 12),
96                  const Text(
97                    'Continue with Google',
98                    style: TextStyle(
99                      fontSize: 16,
100                      color: Colors.black87,
101                      fontWeight: FontWeight.w600,
102                    ),
103                  ),
104                ],
105              ),
106            ),
107          ),
108        ],
109      ),
110    );
111  }
112
113  Widget _buildProfileView() {
114    final user = userCredential.value?.user;
115    return Center(
116      child: Container(
117        margin: const EdgeInsets.all(20),
118        padding: const EdgeInsets.all(20),
119        decoration: BoxDecoration(
120          color: Colors.white,
121          borderRadius: BorderRadius.circular(20),
122          boxShadow: [
123            BoxShadow(
124              color: Colors.grey.withOpacity(0.1),
125              spreadRadius: 1,
126              blurRadius: 10,
127              offset: const Offset(0, 3),
128            ),
129          ],
130        ),
131        child: Column(
132          mainAxisSize: MainAxisSize.min,
133          children: [
134            CircleAvatar(
135              radius: 50,
136              backgroundColor: Colors.blue.withOpacity(0.2),
137              child: Text(
138                user?.displayName?.substring(0, 1).toUpperCase() ?? 'U',
139                style: const TextStyle(
140                  fontSize: 32,
141                  fontWeight: FontWeight.bold,
142                  color: Colors.blue,
143                ),
144              ),
145            ),
146            const SizedBox(height: 24),
147            Text(
148              user?.displayName ?? 'User',
149              style: const TextStyle(
150                fontSize: 24,
151                fontWeight: FontWeight.bold,
152                color: Colors.black87,
153              ),
154            ),
155            const SizedBox(height: 8),
156            Text(
157              user?.email ?? '',
158              style: TextStyle(
159                fontSize: 16,
160                color: Colors.grey[600],
161              ),
162            ),
163            const SizedBox(height: 32),
164            ElevatedButton(
165              onPressed: () async {
166                bool result = await signOutFromGoogle();
167                if (result) {
168                  userCredential.value = null;
169                }
170              },
171              style: ElevatedButton.styleFrom(
172                backgroundColor: Colors.red[400],
173                padding: const EdgeInsets.symmetric(
174                  horizontal: 32,
175                  vertical: 16,
176                ),
177                shape: RoundedRectangleBorder(
178                  borderRadius: BorderRadius.circular(30),
179                ),
180              ),
181              child: const Row(
182                mainAxisSize: MainAxisSize.min,
183                children: [
184                  Icon(Icons.logout),
185                  SizedBox(width: 8),
186                  Text(
187                    'Sign Out',
188                    style: TextStyle(
189                      fontSize: 16,
190                      fontWeight: FontWeight.w600,
191                    ),
192                  ),
193                ],
194              ),
195            ),
196          ],
197        ),
198      ),
199    );
200  }
201}

Google Sign in code#

JavaScript
1Future<dynamic> signInWithGoogle() async {
2    try {
3      final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();
4
5      final GoogleSignInAuthentication? googleAuth =
6          await googleUser?.authentication;
7
8      final credential = GoogleAuthProvider.credential(
9        accessToken: googleAuth?.accessToken,
10        idToken: googleAuth?.idToken,
11      );
12
13      return await FirebaseAuth.instance.signInWithCredential(credential);
14    } on Exception catch (e) {
15      // TODO
16      print('exception->$e');
17    }
18  }

Google Sign-out Code#

JavaScript
1Future<bool> signOutFromGoogle() async {
2    try {
3      await FirebaseAuth.instance.signOut();
4      return true;
5    } on Exception catch (_) {
6      return false;
7    }
8  }

Conclusion#

With the Flutter SDK and Firebase fully integrated, you are now set up to build a cross-platform application that supports Firebase Authentication and other Firebase services. This setup provides a strong foundation for your Flutter project, ensuring you can easily scale and add functionalities, such as Google sign-in, in a seamless way. Continue exploring Flutter’s vast ecosystem and Firebase’s powerful backend services to add more features and build a robust application. Happy coding!

FlutterMobile App DevelopmentFirebase IntegrationGoogle AuthenticationAndroid and iOS Setup