Let’s create a Flutter Firebase app and connect Firebase to the Flutter project. This is crucial, especially if you plan to use Firebase services like authentication, Firestore, or Firebase Cloud Messaging. Here’s a guide on how to connect Firebase in a Flutter project:
Step 1: Create a Firebase project
- Go to the Firebase Console.
- Click on “Add Project”.
- Follow the instructions to create a new project.
- Once the project is created, click on “Continue”.
Step 2: Register your app with Firebase
- After creating the project, click on “Add app”.
- Choose the appropriate platform (Android or iOS) and follow the setup instructions.
- For Android:
- Android package name: Your Flutter project’s package name (e.g.,
com.example.myapp
). - Optionally, you can add a nickname for this app.
- Click on “Register app”.
- Download the
google-services.json
file and place it inside theandroid/app
directory in your Flutter project. - For iOS:
- iOS bundle ID: Your Flutter project’s iOS bundle ID (e.g.,
com.example.myapp
). - Optionally, you can add a nickname for this app.
- Click on “Register app”.
- Download the
GoogleService-Info.plist
file and add it to theios/Runner
directory in your Flutter project.
Step 3: Add Firebase SDK to your Flutter project
- Open your Flutter project in an IDE (e.g., Visual Studio Code).
- Add the Firebase SDK to your Flutter app:
- Open the
pubspec.yaml
file. - Add the
firebase_core
and any other Firebase packages you intend to use. For example:
dependencies:
flutter:
sdk: flutter
firebase_core: ^1.0.0
firebase_auth: ^3.0.0 # If you plan to use Firebase Authentication
cloud_firestore: ^3.0.0 # If you plan to use Firestore
- Save the file.
Runflutter pub get
to install the dependencies.
Step 4: Initialize Firebase in your Flutter app
- Open your
main.dart
file. - Import the necessary packages:
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
Initialize Firebase in the main()
function before running the app:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
Ensure you add the Google services plugin at the bottom of the android/app/build.gradle
file (just before the last line }
):
apply plugin: 'com.google.gms.google-services'
On iOS, ensure you add the following in the ios/Runner/AppDelegate.swift
file:
import UIKit
import Flutter
import Firebase
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
FirebaseApp.configure()
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
Step 5: Usage
After these steps, Firebase is now connected to your Flutter project, and you can start using Firebase services such as Authentication, Firestore, etc., in your Flutter app.
Here’s an example of how to use Google Sign-In with Firebase Authentication in your Flutter app:
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Medium App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn googleSignIn = GoogleSignIn();
Future<User?> _handleSignIn() async {
try {
final GoogleSignInAccount? googleSignInAccount = await googleSignIn.signIn();
final GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount!.authentication;
final AuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken,
);
final UserCredential authResult = await _auth.signInWithCredential(credential);
final User? user = authResult.user;
assert(!user!.isAnonymous);
assert(await user!.getIdToken() != null);
final User? currentUser = await _auth.currentUser;
assert(user!.uid == currentUser!.uid);
print('signInWithGoogle succeeded: $user');
return user;
} catch (error) {
print(error);
return null;
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Medium App'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
_handleSignIn()
.then((User? user) => print(user))
.catchError((e) => print(e));
},
child: Text('Sign in with Google'),
),
),
);
}
}
With these steps, Firebase is successfully integrated into your Flutter app, allowing you to use Firebase services such as Authentication, Firestore, etc.