首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >相关的导致错误的小部件是: FutureBuilder<FirebaseApp>

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

Stack Overflow用户
提问于 2022-03-11 10:04:02
回答 2查看 1.4K关注 0票数 0

我想这个错误与将来的异步函数是相关的,但是我不知道该修复什么。

小部件库╞═══════════════════════════════════════════════════════════捕获的AppModule初始化的══╡异常以下UnsupportedError引发构建FutureBuilder(脏,状态:_FutureBuilderState#38237):不支持的操作: Platform._operatingSystem

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

FutureBuilder:file:///C:/Users/Iradukunda%20Didier/imibonano/lib/app/app_widget.dart:17:12

当异常被抛出时,这是堆栈: 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 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获取C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/io/platform.dart 153:47获取isIOS 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软件包/imibonano/app/app_widget.dart 11:64

_appTheme包/imibonano/app/app_widget.dart 53:43包/颤振/src/小部件/异步615:48

构建包/颤振/src/widget/framework.dart.4904 4904:27

构建包/颤振/src/widget/framework.dart.src 4788:15

performRebuild包/颤振/src/widgets/Frawork.DART 4962:11

performRebuild包/颤振/src/widget/framework.dart.4511 4511:5

重建包/颤振/src/widget/framework.dart.2713 2713:18

buildScope包/颤振/src/小部件/binding.dart 882:9

drawFrame包/flutter/src/呈现/binding.dart 363:5个_handlePersistentFrameCallback包/_handlePersistentFrameCallback/src/调度器/binding.dart 1144:15

_invokeFrameCallback包/flutter/src/调度程序/binding.DART 1081:9

handleDrawFrame包/flutter/src/调度程序/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

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

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

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
<!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里

代码语言:javascript
运行
复制
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,
      ),
    ));
  });
}
EN

回答 2

Stack Overflow用户

发布于 2022-03-11 10:38:17

CLI:在CLI添加之后,在main方法中初始化

代码语言:javascript
运行
复制
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(const MyApp());
}

手动安装:您还没有为web添加依赖项。您需要在web/index.html中第一个依赖项,如flutterfire文档所述。

您需要将下面的行添加到网页正文中。

代码语言:javascript
运行
复制
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script>

此外,您还需要使用以下方法初始化firebase应用程序

代码语言:javascript
运行
复制
<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>
票数 1
EN

Stack Overflow用户

发布于 2022-03-16 10:32:19

如果您正在手动为颤振web安装防火墙,则需要在您的main.dart文件中添加这些代码。

代码语言:javascript
运行
复制
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文件中,添加以下内容(就在脚本标记下面):

代码语言:javascript
运行
复制
   <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>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71436796

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档