简体   繁体   English

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

[英]The relevant error-causing widget was: FutureBuilder<FirebaseApp>

I guess this error is relevant with future async function, but I am not sure where to fix.我猜这个错误与未来的异步 function 有关,但我不确定在哪里修复。

-- AppModule INITIALIZED ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════ The following UnsupportedError was thrown building FutureBuilder(dirty, state: _FutureBuilderState#38237): Unsupported operation: Platform._operatingSystem - AppModule初始化══╡小部件库捕获的异常╞═════════════════════════════════════ ══════════════════════以下UnsupportedError was thrown building FutureBuilder(dirty, state: _FutureBuilderState#38237): Unsupported operation: Platform._operatingSystem

The relevant error-causing widget was: FutureBuilder导致错误的相关小部件是:FutureBuilder
FutureBuilder:file:///C:/Users/Iradukunda%20Didier/imibonano/lib/app/app_widget.dart:17:12 FutureBuilder:file:///C:/Users/Iradukunda%20Didier/imibonano/lib/app/app_widget.dart:17:12

When the exception was thrown, this was the stack: C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/ internal/js_dev_runtime/private/ddc_runtime/errors.dart 251:49 throw C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/io_patch.dart 244:5 _operatingSystem C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/io/platform_impl.dart 56:40 get operatingSystem C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/io/platform.dart 64:45 get _operatingSystem C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 839:8 get C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/io/platform.dart 153:47 get isIOS C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.8当抛出异常时,这是堆栈:C: /b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/internal/js_dev_runtime/private/ddc_runtime/errors.dart 251 :49 投掷C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/io_patch.dart 244:5 _operatingSystem C:/b/s/ w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/io/platform_impl.dart 56:40 获取操作系统 C:/b/s/w/ir/cache/builder/src/out/host_debug /dart-sdk/lib/io/platform.dart 64:45 获取 _operatingSystem C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ ddc_runtime/operations.dart 839:8 获取 C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/io/platform.dart 153:47 获取 isIOS 881037565/86388 /s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.8 8252422964688 839:8 get packages/imibonano/app/app_widget.dart 11:64 8252422964688 839:8 获取包/imibonano/app/app_widget.dart 11:64
_appTheme packages/imibonano/app/app_widget.dart 53:43 packages/flutter/src/widgets/async.dart 615:48 _appTheme 包/imibonano/app/app_widget.dart 53:43 包/flutter/src/widgets/async.dart 615:48
build packages/flutter/src/widgets/framework.dart 4904:27构建包/flutter/src/widgets/framework.dart 4904:27
build packages/flutter/src/widgets/framework.dart 4788:15构建包/flutter/src/widgets/framework.dart 4788:15
performRebuild packages/flutter/src/widgets/framework.dart 4962:11 performRebuild packages/flutter/src/widgets/framework.dart 4962:11
performRebuild packages/flutter/src/widgets/framework.dart 4511:5 performRebuild packages/flutter/src/widgets/framework.dart 4511:5
rebuild packages/flutter/src/widgets/framework.dart 2713:18重建包/flutter/src/widgets/framework.dart 2713:18
buildScope packages/flutter/src/widgets/binding.dart 882:9 buildScope packages/flutter/src/widgets/binding.dart 882:9
drawFrame packages/flutter/src/rendering/binding.dart 363:5 [_handlePersistentFrameCallback] packages/flutter/src/scheduler/binding.dart 1144:15 drawFrame packages/flutter/src/rendering/binding.dart 363:5 [_handlePersistentFrameCallback] packages/flutter/src/scheduler/binding.dart 1144:15
[_invokeFrameCallback] packages/flutter/src/scheduler/binding.dart 1081:9 [_invokeFrameCallback] packages/flutter/src/scheduler/binding.dart 1081:9
handleDrawFrame packages/flutter/src/scheduler/binding.dart 862:7 handleDrawFrame 包/flutter/src/scheduler/binding.dart 862:7
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/isolate_helper.dart 48:19 internalCallback C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/isolate_helper.dart 48:19 internalCallback

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

The relevant error-causing widget was: app_widget导致错误的相关小部件是: 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 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>

in my main.dart在我的 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,
      ),
    ));
  });
}

CLI: After added by CLI, Initialize the firebase in main method as CLI:通过CLI添加后,在main方法中初始化firebase为

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

Manual Installation: You have not added dependencies for web. You need to first dependencies in the web/index.html as stated by [flutterfire documentation][1]手动安装:您尚未添加 web 的依赖项。您需要首先在 web/index.html 中添加依赖项,如 [flutterfire 文档][1] 所述

You need to add the below line to the body of the web page.您需要将以下行添加到 web 页面的正文中。

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

And also you need to initialize the firebase app using following您还需要使用以下方法初始化 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>

If you are manually installing firebase for flutter web you need to add these codes in your main.dart file.如果您为 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());
}

in the index.html file of the web folder, add these(just below the script tag):在 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 找不到 MediaQuery 小部件祖先。相关的导致错误的小部件是 FutureBuilder<FirebaseApp> - No MediaQuery widget ancestor found.The relevant error-causing widget was FutureBuilder<FirebaseApp> “String”类型不是“index”类型“int”的子类型相关的导致错误的小部件是 FutureBuilder<dynamic></dynamic> - type 'String' is not a subtype of type 'int' of 'index' The relevant error-causing widget was FutureBuilder<dynamic> Null 检查运算符用于 null 值相关的导致错误的小部件是 FutureBuilder <list<searchmodel> &gt; </list<searchmodel> - Null check operator used on a null value The relevant error-causing widget was FutureBuilder<List<SearchModel>> 相关的导致错误的小部件是:Scaffold - The relevant error-causing widget was: Scaffold 导致错误的相关小部件是 TextField - The relevant error-causing widget was TextField 相关的导致错误的小部件是 Scaffold - The relevant error-causing widget was Scaffold Flutter dart 错误(相关的导致错误的小部件是...) - Flutter dart error (The relevant error-causing widget was ...) flutter 错误,相关的导致错误的小部件是 Scaffold - flutter error , The relevant error-causing widget was Scaffold 相关的导致错误的小部件是 StreamBuilder <querysnapshot<object?> &gt; </querysnapshot<object?> - The relevant error-causing widget was StreamBuilder<QuerySnapshot<Object?>> 断言失败,相关的导致错误的小部件是 textformfield - failed assertion the relevant error-causing widget was textformfield
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM