Firebase in Flutter: How to connect to Firebase database using Flutter

Author: Zen and the Art of Computer Programming

Firebase in Flutter: How to connect to Firebase database using Flutter

As an artificial intelligence expert, programmer and software architect, I am often attracted by the technical charm of Flutter. Flutter, as a hybrid programming language of Kotlin and JavaScript, has an efficient, fast, and beautiful development experience. At the same time, Flutter is also the first choice recommended by Google for cross-platform mobile application development. In Flutter, Firebase database has become an essential tool for many developers. So, how to use Flutter to connect to Firebase database? This article will give you detailed answers.

  1. introduction

1.1. Background introduction

With the rapid development of mobile Internet, mobile application development has gradually become an important part of my country's software industry. Flutter, as Google's first choice for cross-platform mobile application development, provides developers with an efficient, fast, and beautiful development experience. In Flutter, developers can use Firebase database to store and manage application data.

1.2. Purpose of the article

This article aims to provide Flutter developers with detailed steps and techniques for connecting to Firebase database, and to help developers better use Flutter to build their own mobile applications.

1.3. Target audience

This article will be mainly for Flutter developers, as well as beginners who want to know how Flutter developers connect to Firebase database.

  1. Technical principles and concepts

2.1. Explanation of basic concepts

Firebase is a back-end service provided by Google, which provides a series of cloud functions, databases, storage and other functions. Firebase easily integrates with Flutter applications, providing developers with a way to quickly build and extend Flutter applications.

2.2. Introduction to technical principles

This article will use Firebase Realtime Database as the database, which is a NoSQL real-time database that can store and obtain data in real time. In Flutter, we can store application data through Firebase Realtime Database and obtain data to update the application UI when needed.

2.3. Comparison of related technologies

Firebase Realtime Database has the following advantages compared with other NoSQL databases (such as Django's Python database, MongoDB, etc.):

  • Real-time: Supports real-time data access, can obtain and upload data in real time, and meet the real-time needs of applications.
  • Cross-platform: Supports cross-platform mobile applications and web applications.
  • No programming required: You can use the various features of the database without writing any code.
  • Cloud Hosting: Fully hosted by Google Cloud, ensuring data security and reliability.
  1. Implementation steps and processes

3.1. Preparation: environment configuration and dependency installation

First, you need to make sure your Flutter app is downloaded on Google Play. Then you need to install Firebase. For Android apps, you can follow these steps to install them:

// 对于Android 9.0及更高版本,请使用Firebase CLI初始化
if (Platform.isAndroid()) {
  void installFirebase() {
    final String installationUrl = "https://firebase.google.com/auth/360l7";
    final String authToken = await GoogleAuth.getInstance().defaultInstance.authorizeCode(
      installationUrl,
      "_0yRGbz-V78wXcNj6Q0-zjV1-_1"
    );

    final String databaseURL = "https://firebase.google.com/ Realtime Database";
    final String projectId = "YOUR_PROJECT_ID";

    Firebase.initializeApp(
      authToken,
      databaseURL,
      projectId
    );
  }

  installFirebase();
} else {
  // 对于Android 8.0及更低版本,请使用Android Studio初始化
  void installFirebase() {
    AndroidStudio.Installer.getInstance().getProjectComponent(
      "com.google.firebase",
      "com.google.firebase.firebaseapp",
      "YOUR_APPLICATION_ID"
    ).start(true);

    final String databaseURL = "https://firebase.google.com/ Realtime Database";
    final String projectId = "YOUR_PROJECT_ID";

    Firebase.initializeApp(
      null,
      databaseURL,
      projectId
    );
  }

  installFirebase();
}

For iOS apps, you can install them using build tools like CocoaPods or Fastlane.

3.2. Core module implementation

In the Flutter project, we need to create a custom Firebase client to connect to the Firebase database. First, add the Firebase dependency in the pubspec.yaml file:

dependencies:
  cloud_firestore: ^3.1.7
  firebase_core: ^0.10.6

Next, we need to create a method to initialize Firebase in the application's build.dart file. In the FirebaseService.dart file, you can implement the following code:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';

final FirebaseApp _firebaseApp = FirebaseApp.getInstance();

Future<void> _initializeFirebase() async {
  if (Platform.isAndroid()) {
    final installationUrl = "https://firebase.google.com/auth/360l7";
    final authToken = await GoogleAuth.getInstance().defaultInstance.authorizeCode(
      installationUrl,
      "_0yRGbz-V78wXcNj6Q0-zjV1-_1"
    );

    final databaseURL = "https://firebase.google.com/ Realtime Database";
    final projectId = "YOUR_PROJECT_ID";

    Firebase.initializeApp(
      authToken,
      databaseURL,
      projectId
    );
  } else {
    final AndroidInstaller = AndroidStudio.Installer.getInstance();
    final packageManager = AndroidInstaller.getPackageManager();

    final installationUrl = "https://firebase.google.com/auth/360l7";
    final String authToken = await AndroidAuth.getInstance().defaultInstance.authorizeCode(
      installationUrl,
      "_0yRGbz-V78wXcNj6Q0-zjV1-_1"
    );

    final databaseURL = "https://firebase.google.com/ Realtime Database";
    final projectId = "YOUR_PROJECT_ID";

    AndroidInstaller.install(
      packageManager,
      installationUrl,
      "com.google.firebase",
      "com.google.firebase.firebaseapp",
      packageManager.getMost RecentError(),
      "YOUR_APPLICATION_ID",
      projectId,
      null,
      null
    );

    Firebase.initializeApp(
      null,
      databaseURL,
      projectId
    );
  }
}

After initializing Firebase, you can call initializeAppthe method to set the parameters of Firebase, for example:

_initializeFirebase();

3.3. Integration and testing

After completing the writing of the core module, we can perform integration testing. First, in main.dartthe file, we need to create a test library and call initializeFirebasethe method to initialize Firebase:

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'FlutterFirebase Demo',
      home: Scaffold(
        appBar: AppBar(
          title: Text('FlutterFirebase Demo',
          style: Theme.of(context),
        ),
        body: Text(
          '欢迎来到FlutterFirebase Demo,请确保您已经安装了Firebase并设置了YOUR_PROJECT_ID。',
        ),
      ),
      child: Center(
        child: Text(
          '开始演示Flutter如何连接Firebase数据库,请按“开始”按钮。',
          onPressed: () {
            if (!FirebaseApp.getInstance().getProjectId().isEmpty) {
              // 初始化Firebase
              _initializeFirebase();

              // 在此处添加使用Firebase的代码

              // 显示一个成功的提示信息
              Text('FlutterFirebase Demo已成功初始化!');
            } else {
              Text('请确保您已经设置YOUR_PROJECT_ID。');
            }
          },
        ),
      ),
    );
  }
}

In firebase_services.dartthe file, you write code that uses Firebase. For example, you could write a method to get the ID of a Firebase project:

import 'package:cloud_firestore/cloud_firestore.dart';

Future<String> _getProjectId() async {
  final ProjectSnapshot projectSnapshot = await FirebaseFirestore.instance.collection("projects")
     .where("id.YOUR_PROJECT_ID", FirebaseFirestore.getInstance().projectId)
     .get();

  if (projectSnapshot.empty) {
    throw Exception("项目ID不存在");
  }

  return projectSnapshot.docs[0].id.toString();
}

In your application, you can also use these methods to get data from Firebase.

  1. Application examples and code implementation explanations

Next, we'll create a simple Flutter application that demonstrates how to use Firebase to store and read data. In firebase_services.dartthe file you can write the following code:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';

void _addDataToFirebase() async {
  final projectId = await _getProjectId();

  final db = FirebaseFirestore.instance;
  final ref = db.collection("myCollection");

  await ref.add({
    "title": "床",
    "price": 500,
    "description": "床",
  });
}

Future<void> _initializeFirebase() async {
  if (Platform.isAndroid()) {
    final installationUrl = "https://firebase.google.com/auth/360l7";
    final authToken = await GoogleAuth.getInstance().defaultInstance.authorizeCode(
      installationUrl,
      "_0yRGbz-V78wXcNj6Q0-zjV1-_1"
    );

    final databaseURL = "https://firebase.google.com/ Realtime Database";
    final projectId = "YOUR_PROJECT_ID";

    Firebase.initializeApp(
      authToken,
      databaseURL,
      projectId
    );
  } else {
    final AndroidInstaller = AndroidStudio.Installer.getInstance();
    final packageManager = AndroidInstaller.getPackageManager();

    final installationUrl = "https://firebase.google.com/auth/360l7";
    final String authToken = await AndroidAuth.getInstance().defaultInstance.authorizeCode(
      installationUrl,
      "_0yRGbz-V78wXcNj6Q0-zjV1-_1"
    );

    final databaseURL = "https://firebase.google.com/ Realtime Database";
    final projectId = "YOUR_PROJECT_ID";

    AndroidInstaller.install(
      packageManager,
      installationUrl,
      "com.google.firebase",
      "com.google.firebase.firebaseapp",
      packageManager.getMostRecentError(),
      "YOUR_APPLICATION_ID",
      projectId,
      null,
      null
    );

    Firebase.initializeApp(
      null,
      databaseURL,
      projectId
    );
  }
}

In MyAppthe class, you can write a _addDataToFirebasemethod to add data to Firebase:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';

void _addDataToFirebase() async {
  final projectId = await _getProjectId();

  final db = FirebaseFirestore.instance;
  final ref = db.collection("myCollection");

  await ref.add({
    "title": "床",
    "price": 500,
    "description": "床",
  });
}

You can also write a _getProjectIdmethod to get the Firebase project's ID:

import 'package:cloud_firestore/cloud_firestore.dart';

Future<String> _getProjectId() async {
  final ProjectSnapshot projectSnapshot = await FirebaseFirestore.instance.collection("projects")
     .where("id.YOUR_PROJECT_ID", FirebaseFirestore.getInstance().projectId)
     .get();

  if (projectSnapshot.empty) {
    throw Exception("项目ID不存在");
  }

  return projectSnapshot.docs[0].id.toString();
}

In your application, you can also use these methods to get data from Firebase.

  1. Optimization and improvement

In a real application, you may need to optimize and improve the code. Here are some common optimization tips:

  • Avoid declarations in the AndroidManifest.xml file android:exported.
  • Use finalthe keyword to declare variables.
  • Use whenstatements to handle asynchronous operations.
  • Use voidinstead of voiddeclared functions, which avoids creating a null pointer exception at runtime.
  • When writing test code, avoid using it in test methods await.
  • On Android, avoid using finally.
  • In iOS, avoid using do-catchthe statement.
  • Use isolatethe keyword to avoid naming conflicts.
  • Use constthe keyword to declare constants.
  • newAvoid using operators in your code .
  1. Conclusion and Outlook

Firebase in Flutter is a powerful tool that helps developers quickly build and extend Flutter applications. By using Firebase, you can easily connect to a Firebase database and store and read data using Firebase in your Flutter application.

During the actual development process, you may find some areas that can be improved and optimized. The above are some common optimization tips that can help you improve the performance and stability of your Flutter application.

  1. Appendix: Frequently Asked Questions and Answers

Here are some common Firebase questions and answers:

  • Q: How to use Firebase to store data in Android applications? Answer: To use Firebase to store data in your Android app, follow these steps:

    1. Declare the Firebase service in the AndroidManifest.xml file:

      <manifest xmlns:android="http://schemas.android.com/apk/res/android"
         package="com.example.myapp">
      ...
      <application>
      ...
      <service
      name="com.example.myapp.FirebaseAppService"
      android:name="com.example.myapp.FirebaseAppService"
      android:enabled="true"
      startService="default"
      exported="true">
      <intent-filter>
       <action android:name="com.google.firebase.FirebaseStartActivity" />
       <category android:name="com.google.firebase.FirebaseCategory.MESSAGING" />
      </intent-filter>
      </service>
      </application>
      ...
      </manifest>
    2. Add the Firebase dependency in your application's build.gradle file:

      dependencies {
      ...
      implementation 'com.google.firebase:firebase-auth:19.0.0'
      implementation 'com.google.firebase:firebase-firestore:19.0.0'
      }
    3. In your application's code, initialize Firebase and Firestore:

      import 'package:firebase_core/firebase_core.dart';
      import 'package:firebase_auth/firebase_auth.dart';
      import 'package:firebase_firestore/firebase_firestore.dart';
      

void _initializeFirebase() { FirebaseApp.initializeApp();

// Initialize Firestore FirebaseFirestore.initializeApp(); }


    4. 要获取 Firebase 中的数据,请使用 FirebaseFirestore 或 FirebaseDatabase:

import 'package:firebase_firestore/firebase_firestore.dart';

Future _getData() async { final db = FirebaseFirestore.instance; final query = FirebaseFirestore.Query();

try { final documentSnapshot = await query.get();

if (documentSnapshot.exists) {
  return documentSnapshot.docs[0];
} else {
  throw Exception('没有数据');
}

} catch (e) { throw e; } }


    5. 如何停止 Firebase?
答:您可以使用 `FirebaseApp` 的 `stopFirebase()` 方法来停止 Firebase。这将停止 Firebase 的服务,并释放已经获得的资源。

FirebaseApp.stopFirebase();


    6. 如何创建 Firebase 项目?
答:要创建 Firebase 项目,请按照以下步骤进行:
    1. 在 AndroidManifest.xml 文件中声明 Firebase 服务:

... ... ...


    2. 在应用程序的 build.gradle 文件中添加 Firebase 依赖:

dependencies { ... implementation 'com.google.firebase:firebase-auth:19.0.0' implementation 'com.google.firebase:firebase-firestore:19.0.0' }


    3. 在应用程序的代码中,初始化 Firebase 和 Firestore:

import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_firestore/firebase_firestore.dart';

void _initializeFirebase() { FirebaseApp.initializeApp();

// Initialize Firestore FirebaseFirestore.initializeApp(); }


    4. 要获取 Firebase 中的数据,请使用 FirebaseFirestore 或 FirebaseDatabase:

import 'package:firebase_firestore/firebase_firestore.dart';

Future _getData() async { final db = FirebaseFirestore.instance; final query = FirebaseFirestore.Query();

try { final documentSnapshot = await query.get();

if (documentSnapshot.exists) {
  return documentSnapshot.docs[0];
} else {
  throw Exception('没有数据');
}

} catch (e) { throw e; } }


    5. 如何停止 Firebase?
答:您可以使用 `FirebaseApp` 的 `stopFirebase()` 方法来停止 Firebase 的服务,这将停止 Firebase 的服务,并释放已经获得的资源。

FirebaseApp.stopFirebase();


    6. 如何创建 Firebase 项目?
答:要创建 Firebase 项目,请按照以下步骤进行:
    1. 在 AndroidManifest.xml 文件中声明 Firebase 服务:

... ... ...


    2. 在应用程序的 build.gradle 文件中添加 Firebase 依赖:

dependencies { ...

Guess you like

Origin blog.csdn.net/universsky2015/article/details/131486346