在 Web 浏览器中使用 Firebase 后端运行 Flutter 应用程序

Posted

技术标签:

【中文标题】在 Web 浏览器中使用 Firebase 后端运行 Flutter 应用程序【英文标题】:run flutter application with firebase backend in web browser 【发布时间】:2022-01-01 17:52:15 【问题描述】:

我从一周开始就遇到这个问题,我在网络上尝试了所有方法,但仍然是同样的问题,这里是带有 firebase 配置的 index.html

<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js"></script>
<script>
    // Import the functions you need from the SDKs you need
  import  initializeApp  from "firebase/app";
  // TODO: Add SDKs for Firebase products that you want to use
  // https://firebase.google.com/docs/web/setup#available-libraries

  // Your web app's Firebase configuration
  // For Firebase JS SDK v7.20.0 and later, measurementId is optional
  const firebaseConfig = 
  apiKey: "jkhkhkhlkjhlkihoihhjkhkllkjhkjhk",
  authDomain: "example",
  projectId: "example",
  storageBucket: "fdsfssfdf",
  messagingSenderId: "dfdfdfdfdf",
  appId: "dsfsdter54545",
  measurementId: "fdfdfsdfsddf"
  ;
initializeApp(firebaseConfig);
</script>
<script src="main.dart.js" type="application/javascript"></script>
  <!-- This script installs service_worker.js to provide PWA functionality to
       application. For more information, see:
       https://developers.google.com/web/fundamentals/primers/service-workers -->
  <script>
    var serviceWorkerVersion = null;
    var scriptLoaded = false;
    function loadMainDartJs() 
      if (scriptLoaded) 
        return;
      
      scriptLoaded = true;
      var scriptTag = document.createElement('script');
      scriptTag.src = 'main.dart.js';
      scriptTag.type = 'application/javascript';
      document.body.append(scriptTag);
    

    if ('serviceWorker' in navigator) 
      // Service workers are supported. Use them.
      window.addEventListener('load', function () 
        // Wait for registration to finish before dropping the <script> tag.
        // Otherwise, the browser will load the script multiple times,
        // potentially different versions.
        var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion;
        navigator.serviceWorker.register(serviceWorkerUrl)
          .then((reg) => 
            function waitForActivation(serviceWorker) 
              serviceWorker.addEventListener('statechange', () => 
                if (serviceWorker.state == 'activated') 
                  console.log('Installed new service worker.');
                  loadMainDartJs();
                
              );
            
            if (!reg.active && (reg.installing || reg.waiting)) 
              // No active web worker and we have installed or are installing
              // one for the first time. Simply wait for it to activate.
              waitForActivation(reg.installing || reg.waiting);
             else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) 
              // When the app updates the serviceWorkerVersion changes, so we
              // need to ask the service worker to update.
              console.log('New service worker available.');
              reg.update();
              waitForActivation(reg.installing);
             else 
              // Existing service worker is still good.
              console.log('Loading app from service worker.');
              loadMainDartJs();
            
          );

        // If service worker doesn't succeed in a reasonable amount of time,
        // fallback to plaint <script> tag.
        setTimeout(() => 
          if (!scriptLoaded) 
            console.warn(
              'Failed to load app from service worker. Falling back to plain <script> tag.',
            );
            loadMainDartJs();
          
        , 4000);
      );
     else 
      // Service workers not supported. Just drop the <script> tag.
      loadMainDartJs();
    
  </script>



</body>
</html>

这是初始化 firebase 的 main.dart

导入'包:firebase_core/firebase_core.dart'; 导入'package:flutter/material.dart';

void main() 
  WidgetsFlutterBinding.ensureInitialized();
  runApp( MyApp());


class MyApp extends StatelessWidget 
   MyApp(Key? key) : super(key: key);
  final Future<FirebaseApp> _initialization = Firebase.initializeApp();
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) 
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: FutureBuilder(
        future: _initialization,
          builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) 
            if (snapshot.hasError) 
              return const Center(child: Text("error with firebase connection"),);
            

            // Once complete, show your application
            if (snapshot.connectionState == ConnectionState.done) 
              return const MyHomePage(title: 'osama test for research');
            

            // Otherwise, show something whilst waiting for initialization to complete
            return const Center(child: CircularProgressIndicator(),);
          ,

    ));
  


class MyHomePage extends StatefulWidget 
  const MyHomePage(Key? key, required this.title) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();


class _MyHomePageState extends State<MyHomePage> 
  int _counter = 0;

  void _incrementCounter() 
    setState(() 
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    );
  

  @override
  Widget build(BuildContext context) 
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  

这里是 pubspec.yaml

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for ios style icons.
  cupertino_icons: ^1.0.2
  firebase_core: ^1.10.0

我发现了这个问题

 Running with sound null safety 
Debug service listening on ws://127.0.0.1:60251/GC2a7MPp7XE=/ws
FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).
    at Object.u [as app] (https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js:1:18836)
    at Object.app$ [as app] (http://localhost:60182/packages/firebase_core_web/src/interop/core.dart.lib.js:31:101)
    at initializeApp (http://localhost:60182/packages/firebase_core_web/firebase_core_web.dart.lib.js:104:25)
    at initializeApp.next (<anonymous>)
    at runBody (http://localhost:60182/dart_sdk.js:40211:34)
    at Object._async [as async] (http://localhost:60182/dart_sdk.js:40242:7)
    at firebase_core_web.FirebaseCoreWeb.new.initializeApp (http://localhost:60182/packages/firebase_core_web/firebase_core_web.dart.lib.js:84:20)
    at initializeApp (http://localhost:60182/packages/firebase_core/firebase_core.dart.lib.js:100:59)
    at initializeApp.next (<anonymous>)
    at runBody (http://localhost:60182/dart_sdk.js:40211:34)
    at Object._async [as async] (http://localhost:60182/dart_sdk.js:40242:7)
    at Function.initializeApp (http://localhost:60182/packages/firebase_core/firebase_core.dart.lib.js:99:20)
    at new main.MyApp.new (http://localhost:60182/packages/research/main.dart.lib.js:393:52)
    at main$ (http://localhost:60182/packages/research/main.dart.lib.js:487:20)
    at main (http://localhost:60182/web_entrypoint.dart.lib.js:36:29)
    at main.next (<anonymous>)
    at http://localhost:60182/dart_sdk.js:40192:33
    at _RootZone.runUnary (http://localhost:60182/dart_sdk.js:40062:59)
    at _FutureListener.thenAwait.handleValue (http://localhost:60182/dart_sdk.js:34983:29)
    at handleValueCallback (http://localhost:60182/dart_sdk.js:35551:49)
    at Function._propagateToListeners (http://localhost:60182/dart_sdk.js:35589:17)
    at _Future.new.[_completeWithValue] (http://localhost:60182/dart_sdk.js:35437:23)
    at http://localhost:60182/dart_sdk.js:34617:46
    at _RootZone.runUnary (http://localhost:60182/dart_sdk.js:40062:59)
    at _FutureListener.then.handleValue (http://localhost:60182/dart_sdk.js:34983:29)
    at handleValueCallback (http://localhost:60182/dart_sdk.js:35551:49)
    at Function._propagateToListeners (http://localhost:60182/dart_sdk.js:35589:17)
    at _Future.new.[_completeWithValue] (http://localhost:60182/dart_sdk.js:35437:23)
    at async._AsyncCallbackEntry.new.callback (http://localhost:60182/dart_sdk.js:35458:35)
    at Object._microtaskLoop (http://localhost:60182/dart_sdk.js:40330:13)
    at _startMicrotaskLoop (http://localhost:60182/dart_sdk.js:40336:13)
    at http://localhost:60182/dart_sdk.js:35811:9

【问题讨论】:

【参考方案1】:

请删除,

  import  initializeApp  from "firebase/app";

并使用

// Initialize Firebase
firebase.initializeApp(firebaseConfig);

【讨论】:

【参考方案2】:

将主函数替换为,

Future main() async 
   WidgetsFlutterBinding.ensureInitialized();
   await Firebase.initializeApp();
   runApp( MyApp());

【讨论】:

不幸的是同样的问题,我已经使用 StreamBuilder 初始化了 firebase

以上是关于在 Web 浏览器中使用 Firebase 后端运行 Flutter 应用程序的主要内容,如果未能解决你的问题,请参考以下文章

使用 AWS SNS 的浏览器通知 [关闭]

无法访问 Cloud Firestore 后端错误

Flutter Web 在 Firebase 托管中不起作用

Flutter Web 显示 Microsoft 文档 Firebase

Flutter web firebase/firestore错误运行

无法解码 Firebase JWT