Flutter Firebase配置

196 阅读2分钟

Flutter Firebase文档

创建项目

创建Firebase项目

我们打开Firebase Console,点击添加项目,我们设置项目名称为flutter-demo

QQ截图20230917154334.png

QQ截图20230917154345.png

QQ截图20230917154359.png

等待项目创建完毕后我们创建Android和iOS项目

QQ截图20230917154516.png

创建Android项目

输入应用包名com.example.flutter_demo,一直点下一步即可,所需的相应配置我们后续通过FirebaseCLI自动生成

QQ截图20230917154616.png

创建iOS项目

输入应用包名com.example.flutterDemo,一直点下一步即可,所需的相应配置我们后续通过FirebaseCLI自动生成

QQ截图20230917155012.png

配置完成后,点击项目设置,即可看到配置项,后续修改

QQ截图20230917155121.png

命令行设置代理(非常重要)

每次的新打开的命令行一定要先执行
windows
set http_proxy=http://127.0.0.1:7890
set https_proxy=http://127.0.0.1:7890

mac
export http_proxy="http://127.0.0.1:7890"
export https_proxy="http://127.0.0.1:7890"

github报错OpenSSL SSL_connect: Connection was reset in connection to github.com:443
git config --global http.proxy 127.0.0.1:7890
git config --global https.proxy 127.0.0.1:7890

//清除git代理
git config --global --unset http.proxy
git config --global --unset https.proxy


校验是否生效
curl https://www.google.com

配置FirebaseCLI

  1. 运行以下命令,使用 npm 安装 Firebase CLI:

    npm install -g firebase-tools
    
    dart pub global activate flutterfire_cli
    
  2. 登录Firebase使用命令

    这里经常会遇到不生效的情况,使用下列命令,手动处理

    firebase login --no-localhost
    

    复制命令行里面的连接到浏览器,进行登陆验证,最后复制验证码,在命令行右键填入

    QQ截图20230917164750.png

    QQ截图20230917164553.png

  3. 配置项目,在你的Flutter项目下运行以下命令,选择对应的Firebase项目,会自动生成配置文件

    flutterfire configure
    

    QQ截图20230917171305.png

    我们看到总共生成了四个文件,如果后续配置有修改,重新生成文件时,建议手动删除这几个文件后再生成

    QQ截图20230917171542.png

问题与解决

可能遇到的问题

  1. 'flutterfire' 不是内部或外部命令,也不是可运行的程序或批处理文件

    解决:运行dart pub global activate flutterfire_cli,并配置下面的环境变量

  2. Pub installs executables into C:\Users\Administrator\AppData\Local\Pub\Cache\bin, which is not on your path. You can fix that by adding that directory to your system's "Path" environment variable. A web search for "configure windows path" will show you how.

    解决:添加C:\Users\Administrator\AppData\Local\Pub\Cache\bin系统环境变量

  3. Unable to authenticate using the provided code. Please try again

    解决:验证码复制后,点击右键填入

  4. Firebase上面的上面修改后,重新生成配置,iOS改动不生效

    解决:如果GoogleService-Info.plist已存在,不会重新生成,删除后再次生成即可

Flutter中使用

添加依赖

使用命令flutter pub add firebase_core或在pubspec.yaml中添加

firebase_core: 2.15.1

main.dart项目入口处添加以下代码

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(MyApp());
}