Connecting Flutter Mobile and Web to Firebase
Published: 2023-08-27 23:06:56

Title: Connecting Flutter Mobile and Web to Firebase
**Introduction: Firebase Integration with Flutter**
Firebase, Google's comprehensive platform, offers a variety of services that empower developers to build high-quality apps quickly. In this article, we'll explore how to seamlessly connect both Flutter mobile and web applications to Firebase services. We'll cover Firebase setup, authentication, and database integration, providing code snippets along the way to facilitate your integration process.
**Setting Up Firebase:**
1. Begin by creating a Firebase project through the [Firebase Console](https://console.firebase.google.com/).
2. For mobile, add your Android and iOS apps to the project. For web, configure the web app.
3. Download the configuration files for each platform and add them to your respective Flutter projects.
**Authentication Integration:**
Firebase offers various authentication methods, including email/password, Google Sign-In, and more. Let's implement Google Sign-In authentication in both mobile and web apps.
**Mobile App Authentication (Google Sign-In):**
```dart
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn googleSignIn = GoogleSignIn();
Future<User?> signInWithGoogle() async {
 try {
 final GoogleSignInAccount? googleSignInAccount = await googleSignIn.signIn();
 if (googleSignInAccount != null) {
 final GoogleSignInAuthentication googleSignInAuth = await googleSignInAccount.authentication;
 final AuthCredential credential = GoogleAuthProvider.credential(
 accessToken: googleSignInAuth.accessToken,
 idToken: googleSignInAuth.idToken,
 );
 final UserCredential authResult = await _auth.signInWithCredential(credential);
 final User? user = authResult.user;
 return user;
 }
 } catch (error) {
 print("Google Sign-In Error: $error");
 return null;
 }
}
```
**Web App Authentication (Google Sign-In):**
```dart
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.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: 'Firebase Web Demo',
 home: MyHomePage(),
 );
 }
}
class MyHomePage extends StatelessWidget {
 final FirebaseAuth _auth = FirebaseAuth.instance;
 final GoogleSignIn googleSignIn = GoogleSignIn(scopes: ['email']);
Future<User?> signInWithGoogle() async {
 try {
 final GoogleSignInAccount? googleSignInAccount = await googleSignIn.signIn();
 if (googleSignInAccount != null) {
 final GoogleSignInAuthentication googleSignInAuth = await googleSignInAccount.authentication;
 final AuthCredential credential = GoogleAuthProvider.credential(
 accessToken: googleSignInAuth.accessToken,
 idToken: googleSignInAuth.idToken,
 );
 final UserCredential authResult = await _auth.signInWithCredential(credential);
 final User? user = authResult.user;
 return user;
 }
 } catch (error) {
 print("Google Sign-In Error: $error");
 return null;
 }
 }
@override
 Widget build(BuildContext context) {
 return Scaffold(
 appBar: AppBar(title: Text('Firebase Web Demo')),
 body: Center(
 child: ElevatedButton(
 onPressed: () => signInWithGoogle(),
 child: Text('Sign In with Google'),
 ),
 ),
 );
 }
}
```
**Realtime Database Integration:**
Firebase Realtime Database provides a cloud-hosted NoSQL database that synchronizes data between clients in real-time.
**Mobile and Web App Realtime Database Integration:**
```dart
import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
class DatabaseExample extends StatelessWidget {
 final DatabaseReference _databaseReference = FirebaseDatabase.instance.reference();
@override
 Widget build(BuildContext context) {
 return StreamBuilder<Event>(
 stream: _databaseReference.child('messages').onValue,
 builder: (context, snapshot) {
 if (snapshot.hasData) {
 final DataSnapshot data = snapshot.data!.snapshot;
 final Map<dynamic, dynamic>? messageMap = data.value;
 final List<String> messages = [];
if (messageMap != null) {
 messageMap.forEach((key, value) {
 messages.add(value);
 });
 }
return ListView.builder(
 itemCount: messages.length,
 itemBuilder: (context, index) {
 return ListTile(title: Text(messages[index]));
 },
 );
 } else {
 return CircularProgressIndicator();
 }
 },
 );
 }
}
```
**Conclusion: Seamless Firebase Integration**
Connecting Flutter mobile and web apps to Firebase services enhances app functionality and user experience. By following these steps and utilizing the provided code snippets, you'll streamline authentication and integrate a realtime database into both platforms. Firebase's versatility and ease of use empower developers to create dynamic and feature-rich applications.

Feel free to explore other Firebase services, such as Cloud Firestore, Cloud Functions, and Cloud Storage, to further enrich your Flutter apps across platforms.
Connect with me on Twitter [@gideonsalamii](https://twitter.com/gideonsalamii) for more Flutter and Firebase insights.
Thank you for reading!