提问者:小点点

相关的导致错误的小部件是:FutureBuilder<FirebaseApp>


我想这个错误与未来的异步功能有关,但我不确定在哪里修复。

--AppModule INITIALIZED的异常被WIDGETS库捕获 ╞═══════════════════════════════════════════════════════════ 下面的不支持的错误被抛出构建FutureBuilder(脏,状态:_FutureBuilderState#38237):不支持的操作:平台。_operatingSystem

导致相关错误的小部件是:FutureBuilder
FutureBuilder: file:///C:/用户/伊拉克昆达·迪迪埃/imibonano/lib/app/app_widget.dart:17:12

════════════════════════════════════════════════════════════════════════════════════════════════════

相关的导致错误的小部件是:app_widget

class AppWidget extends StatelessWidget {
  final bool isDark;
  AppWidget({Key? key, required this.isDark}) : super(key: key);

  final Future<FirebaseApp> _inicializacao = Firebase.initializeApp();

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: _inicializacao,
        builder: (_, snapshot) {
          if (snapshot.hasError) {
            return Center(
                child: Text(
              "Error: ${snapshot.hasError}",
              style: TextStyle(fontSize: 22),
              textDirection: TextDirection.ltr,
            ));
          }
          if (snapshot.connectionState == ConnectionState.done) {
            return MaterialApp(
              builder: (context, widget) => ResponsiveWrapper.builder(
                  BouncingScrollWrapper.builder(context, widget!),
                  maxWidth: 1200,
                  minWidth: 400,
                  defaultScale: true,
                  breakpoints: [
                    ResponsiveBreakpoint.resize(400, name: MOBILE),
                    ResponsiveBreakpoint.autoScale(800, name: TABLET),
                    ResponsiveBreakpoint.autoScale(1000, name: TABLET),
                    ResponsiveBreakpoint.resize(1200, name: DESKTOP),
                    ResponsiveBreakpoint.autoScale(2460, name: "4K"),
                  ],
                  background: Container(color: Color(0xFFF5F5F5))),
              localizationsDelegates: [
                GlobalMaterialLocalizations.delegate,
                GlobalWidgetsLocalizations.delegate,
              ],
              supportedLocales: [
                const Locale('pt', 'BR'), // portugues
              ],

              /// Retorna uma localidade que será usada pelo aplicativo
              localeResolutionCallback: (locale, supportedLocales) {
                // Verifique se o local do dispositivo atual é compatível
                for (var supportedLocale in supportedLocales) {
                  if (supportedLocale.languageCode == locale!.languageCode) {
                    return supportedLocale;
                  }
                }

                /// Se a localidade do dispositivo não for compatível, use o primeiro
                ///
                return supportedLocales.first;
              },
              title: 'Unimatch',
              theme: isDark ? _appThemeDark() : _appTheme(),
              initialRoute: '/',

              debugShowCheckedModeBanner: false,
            ).modular();
          }

          return CircularProgressIndicator();
        });
  }
}

html

<!DOCTYPE html>
<html>
<head>
  <!--
    If you are serving your web app in a path other than the root, change the
    href value below to reflect the base path you are serving from.

    The path provided below has to start and end with a slash "/" in order for
    it to work correctly.

    For more details:
    * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base

    This is a placeholder for base href that will be replaced by the value of
    the `--base-href` argument provided to `flutter build`.
  -->
  <base href="$FLUTTER_BASE_HREF">

  <meta charset="UTF-8">
  <meta content="IE=Edge" http-equiv="X-UA-Compatible">
  <meta name="description" content="A new Flutter project.">

  <!-- iOS meta tags & icons -->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="apple-mobile-web-app-title" content="uni_match">
  <link rel="apple-touch-icon" href="icons/Icon-192.png">

  <!-- Favicon -->
  <link rel="icon" type="image/png" href="favicon.png"/>

  <title>uni_match</title>
  <link rel="manifest" href="manifest.json">
  <link rel="stylesheet" type="text/css" href="splash/style.css">
</head>
<body style="position: fixed; inset: 0px; overflow: hidden; padding: 0px; margin: 0px; user-select: none; touch-action: none; font: 14px sans-serif; color: red;">
  <!-- 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>
  <picture id="splash">
    <source srcset="splash/img/light-1x.png 1x, splash/img/light-2x.png 2x, splash/img/light-3x.png 3x, splash/img/light-4x.png 4x" media="(prefers-color-scheme: light) or (prefers-color-scheme: no-preference)">
    <source srcset="splash/img/dark-1x.png 1x, splash/img/dark-2x.png 2x, splash/img/dark-3x.png 3x, splash/img/dark-4x.png 4x" media="(prefers-color-scheme: dark)">
    <img class="center" aria-hidden="true" src="splash/img/light-1x.png" />
  </picture>
</body>
</html>

在我的main. dart

void main() async {
  if (defaultTargetPlatform == TargetPlatform.android) {
    InAppPurchaseConnection.enablePendingPurchases();
  }

  WidgetsFlutterBinding.ensureInitialized();

  timeago.setLocaleMessages('pt_BR', timeago.PtBrMessages());

  // Initialize firebase app
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  // Initialize Google Mobile Ads SDK

  if (Platform.isIOS) {
    await FirebaseMessaging.instance
        .setForegroundNotificationPresentationOptions(
      alert: true,
      badge: true,
      sound: true,
    );
  }

  SharedPreferences sharedPreferences = await SharedPreferences.getInstance();

  var resultadoTheme = sharedPreferences.get('dark');
  print(resultadoTheme);

  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitDown,
    DeviceOrientation.portraitUp,
  ]).then((_) {
    runApp(ModularApp(
      module: AppModule(),
      child: AppWidget(
        isDark: resultadoTheme == null ? false : resultadoTheme as bool,
      ),
    ));
  });
}

共2个答案

匿名用户

CLI:添加CLI后,在main方法中初始化火力基地为

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

手动安装:您没有为web添加依赖项。您需要首先在web/index. html中添加依赖项,如[flutterfire留档][1]

您需要将以下行添加到网页正文。

<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script>

您还需要使用以下内容初始化Firebase应用程序

<script>
      var firebaseConfig = {
        apiKey: "...",
        authDomain: "[YOUR_PROJECT].firebaseapp.com",
        databaseURL: "https://[YOUR_PROJECT].firebaseio.com",
        projectId: "[YOUR_PROJECT]",
        storageBucket: "[YOUR_PROJECT].appspot.com",
        messagingSenderId: "...",
        appId: "1:...:web:...",
        measurementId: "G-...",
      };

      // Initialize Firebase
      firebase.initializeApp(firebaseConfig);
    </script>

匿名用户

如果您手动安装flutter web的Firebase,您需要在main. dart文件中添加这些代码。

Future main() async {
WidgetsFlutterBinding.ensureInitialized();
try {
    await Firebase.initializeApp(
      options: const FirebaseOptions(
        apiKey: "apiKey",
        appId: "appId",
        messagingSenderId: "messagingSenderId",
        projectId: "projectId",
      ),
    );
  } on FirebaseException catch (e) {
    if (e.code == 'duplicate-app') {
      await Firebase.initializeApp();
    }
  }
runApp(const MyApp());
}

在Web文件夹的index. html文件中,添加这些(就在脚本标签下方):

   <script type="module">
          import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js";
          const firebaseConfig = {
            apiKey: "...",
            authDomain: "[YOUR_PROJECT].firebaseapp.com",
            databaseURL: "https://[YOUR_PROJECT].firebaseio.com",
            projectId: "[YOUR_PROJECT]",
            storageBucket: "[YOUR_PROJECT].appspot.com",
            messagingSenderId: "...",
            appId: "1:...:web:...",
            measurementId: "G-...",
          };
          const app = initializeApp(firebaseConfig);
   </script>