I guess this error is relevant with future async function, but I am not sure where to fix.
-- AppModule INITIALIZED ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════ The following UnsupportedError was thrown building FutureBuilder(dirty, state: _FutureBuilderState#38237): Unsupported operation: Platform._operatingSystem
The relevant error-causing widget was: FutureBuilder
FutureBuilder:file:///C:/Users/Iradukunda%20Didier/imibonano/lib/app/app_widget.dart:17:12When 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 8252422964688 839:8 get packages/imibonano/app/app_widget.dart 11:64
_appTheme packages/imibonano/app/app_widget.dart 53:43 packages/flutter/src/widgets/async.dart 615:48
build packages/flutter/src/widgets/framework.dart 4904:27
build packages/flutter/src/widgets/framework.dart 4788:15
performRebuild packages/flutter/src/widgets/framework.dart 4962:11
performRebuild packages/flutter/src/widgets/framework.dart 4511:5
rebuild packages/flutter/src/widgets/framework.dart 2713:18
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
[_invokeFrameCallback] packages/flutter/src/scheduler/binding.dart 1081:9
handleDrawFrame packages/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════════════════════════════════════════════════════════════════════════════════════════════════════
The relevant error-causing widget was: 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>
in my 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
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]
You need to add the below line to the body of the web page.
<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
<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.
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):
<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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.