我正在使用VScode构建一个flutter应用程序。在模拟器上安装apk后,我遇到了一个错误,但应用程序无法启动,模拟器屏幕上出现了一个以下错误:
NoSuchMethodError: The method 'Of' was called on null.
Receiver:Null.
Tried calling: of(Instance of 'StatelessElement')
See also https://flutter.dev/docs/testing/errors
在控制台上检查后,可以看到以下内容:
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY
The following NoSuchMethodError was thrown building Builder(dirty, dependencies:
[_MyappProvider]):
The method 'of' was called on null.
Receiver: null
Tried calling: of(Instance of 'StatelessElement')
The relevant error-causing widget was:
MaterialApp
MaterialApp:file:///C:/App%20Development/MyApp/lib/main.dart:90:16
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:38:5)
#1 LocalizationService.of (package:Myapp/services/localization.dart:43:49)
#2 _MyAppState.bootstrapMyappProviderInContext (package:Myapp/main.dart:240:51)
#3 _MyAppState.build.<anonymous closure> (package:Myapp/main.dart:150:17)
#4 MaterialPageRoute.buildContent (package:flutter/src/material/page.dart:52:55)
#5 MaterialRouteTransitionMixin.buildPage (package:flutter/src/material/page.dart:110:27)
#6 _ModalScopeState.build.<anonymous closure>.<anonymous closure> (package:flutter/src/widgets/routes.dart:906:55)
#7 Builder.build (package:flutter/src/widgets/basic.dart:7372:48)
#8 StatelessElement.build (package:flutter/src/widgets/framework.dart:4949:49)
#9 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4878:15)
#10 Element.rebuild (package:flutter/src/widgets/framework.dart:4604:5)
#11 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4859:5)
#12 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4853:5)
... Normal element mounting (266 frames)
#278 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3863:16)
#279 MultiChildRenderObjectElement.inflateWidget (package:flutter/src/widgets/framework.dart:6435:36)
#280 MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6447:32)
... Normal element mounting (155 frames)
#435 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3863:16)
#436 Element.updateChild (package:flutter/src/widgets/framework.dart:3586:20)
#437 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4904:16)
#438 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:5050:11)
#439 Element.rebuild (package:flutter/src/widgets/framework.dart:4604:5)
#440 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2667:19)
#441 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:882:21)
#442 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:378:5)
#443 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1175:15)
#444 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1104:9)
#445 SchedulerBinding.scheduleWarmUpFrame.<anonymous closure> (package:flutter/src/scheduler/binding.dart:881:7)
(elided 11 frames from class _RawReceivePortImpl, class _Timer, dart:async, and dart:async-patch)
I/flutter (13116): LateInitializationError: Field '_localizationService@197214030' has not been initialized.
I/flutter (13116): #0 HttpieService._localizationService (package:Myapp/services/httpie.dart)
I/flutter (13116): #1 HttpieService._getLanguage (package:Myapp/services/httpie.dart:359:12)
I/flutter (13116): #2 HttpieService._getHeadersWithConfig (package:Myapp/services/httpie.dart:373:65)
I/flutter (13116): #3 HttpieService.get (package:Myapp/services/httpie.dart:223:24)
I/flutter (13116): #4 DocumentsService.getCommunityGuidelines (package:Myapp/services/documents.dart:30:50)
I/flutter (13116): #5 DocumentsService.preload (package:Myapp/services/documents.dart:19:5)
I/flutter (13116): #6 MyappProviderState.initAsyncState (package:Myapp/provider.dart:242:22)
I/flutter (13116): <asynchronous suspension>
I/flutter (13116): In dev mode. Not sending report to Sentry.io.
I/flutter (13116): LateInitializationError: Field '_localizationService@197214030' has not been initialized.
I/flutter (13116): #0 HttpieService._localizationService (package:Myapp/services/httpie.dart)
I/flutter (13116): #1 HttpieService._getLanguage (package:Myapp/services/httpie.dart:359:12)
I/flutter (13116): #2 HttpieService._getHeadersWithConfig (package:Myapp/services/httpie.dart:373:65)
I/flutter (13116): #3 HttpieService.get (package:Myapp/services/httpie.dart:223:24)
I/flutter (13116): #4 DocumentsService.getPrivacyPolicy (package:Myapp/services/documents.dart:38:50)
I/flutter (13116): #5 DocumentsService.preload (package:Myapp/services/documents.dart:20:5)
I/flutter (13116): #6 MyappProviderState.initAsyncState (package:Myapp/provider.dart:242:22)
I/flutter (13116): <asynchronous suspension>
I/flutter (13116): In dev mode. Not sending report to Sentry.io.
I/flutter (13116): LateInitializationError: Field '_localizationService@197214030' has not been initialized.
I/flutter (13116): #0 HttpieService._localizationService (package:Myapp/services/httpie.dart)
I/flutter (13116): #1 HttpieService._getLanguage (package:Myapp/services/httpie.dart:359:12)
I/flutter (13116): #2 HttpieService._getHeadersWithConfig (package:Myapp/services/httpie.dart:373:65)
I/flutter (13116): #3 HttpieService.get (package:Myapp/services/httpie.dart:223:24)
I/flutter (13116): #4 DocumentsService.getTermsOfUse (package:Myapp/services/documents.dart:46:50)
R Hot restart.
h List all available interactive commands.
d Detach (terminate "flutter run" but leave application running).
c Clear the screen
q Quit (terminate the application on the device).
Running with unsound null safety
For more information see https://dart.dev/null-safety/unsound-null-safety
An Observatory debugger and profiler on sdk gphone64 x86 64 is available at: http://127.0.0.1:60295/QBiGoD5jfGk=/
The Flutter DevTools debugger and profiler on sdk gphone64 x86 64 is available at: http://127.0.0.1:60299?uri=http://127.0.0.1:60295/QBiGoD5jfGk=/
D/ProfileInstaller(13116): Installing profile for .myapp.app.dev
Application finished.
导致问题的代码:Main.dartfinal RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();
class MyApp extends StatefulWidget {
final MyappProviderKey = GlobalKey<MyappProviderState>();
MyApp({Key? key}) : super(key: key);
@override
// ignore: library_private_types_in_public_api
_MyAppState createState() => _MyAppState();
static void setLocale(BuildContext context, Locale? newLocale) {
_MyAppState? state = context.findAncestorStateOfType<_MyAppState>();
state?.setState(() {
state.locale = newLocale ?? const Locale('en', 'US');
});
}
}
class _MyAppState extends State<MyApp> {
Locale? locale;
late bool _needsBootstrap;
static const MAX_NETWORK_IMAGE_CACHE_MB = 200;
static const MAX_NETWORK_IMAGE_CACHE_ENTRIES = 1000;
@override
void initState() {
super.initState();
_needsBootstrap = true;
}
void bootstrap() {
DiskCache().maxEntries = MAX_NETWORK_IMAGE_CACHE_ENTRIES;
//DiskCache().maxSizeBytes = MAX_NETWORK_IMAGE_CACHE_MB * 1000000; // 200mb
}
@override
Widget build(BuildContext context) {
if (_needsBootstrap) {
bootstrap();
_needsBootstrap = false;
}
var textTheme = _defaultTextTheme();
return MyappProvider(
key: widget.MyappProviderKey,
child: OBToast(
child: MaterialApp(
navigatorObservers: [routeObserver],
locale: locale,
debugShowCheckedModeBanner: false,
localeResolutionCallback: (deviceLocale, supportedLocales) {
// if no deviceLocale use english
if (deviceLocale == null) {
locale = const Locale('en', 'US');
return locale;
}
// initialise locale from device
if (deviceLocale != null &&
supportedLanguages.contains(deviceLocale.languageCode) &&
locale == null) {
Locale supportedMatchedLocale = supportedLocales.firstWhere(
(Locale locale) =>
locale.languageCode == deviceLocale.languageCode);
locale = supportedMatchedLocale;
} else if (locale == null) {
print(
'Locale ${deviceLocale.languageCode} not supported, defaulting to en');
locale = const Locale('en', 'US');
}
return locale;
},
title: 'Myapp',
supportedLocales: supportedLocales,
localizationsDelegates: const [
LocalizationServiceDelegate(),
GlobalCupertinoLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
MaterialLocalizationPtBRDelegate(),
CupertinoLocalizationPtBRDelegate(),
MaterialLocalizationEsESDelegate(),
CupertinoLocalizationEsESDelegate(),
MaterialLocalizationSvSEDelegate(),
CupertinoLocalizationSvSEDelegate(),
],
theme: ThemeData(
buttonTheme: ButtonThemeData(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(2.0))),
// 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 press Run > Flutter Hot Reload in IntelliJ). Notice that the
// counter didn't reset back to zero; the application is not restarted.
primarySwatch: Colors.grey,
fontFamily: 'NunitoSans',
textTheme: textTheme,
primaryTextTheme: textTheme),
routes: {
/// The MyappProvider uses services available in the context
/// Their connection must be bootstrapped but no other way to execute
/// something before loading any route, therefore this ugliness.
'/': (BuildContext context) {
bootstrapMyappProviderInContext(context);
return const OBHomePage();
},
'/auth': (BuildContext context) {
bootstrapMyappProviderInContext(context);
return const OBAuthSplashPage();
},
'/auth/token': (BuildContext context) {
bootstrapMyappProviderInContext(context);
return const OBAuthCreateAccountPage();
},
'/auth/get-started': (BuildContext context) {
bootstrapMyappProviderInContext(context);
return const OBAuthGetStartedPage();
},
'/auth/legal_step': (BuildContext context) {
bootstrapMyappProviderInContext(context);
return const OBLegalStepPage();
},
'/auth/accept_step': (BuildContext context) {
bootstrapMyappProviderInContext(context);
return const OBAcceptStepPage();
},
'/auth/name_step': (BuildContext context) {
bootstrapMyappProviderInContext(context);
return const OBAuthNameStepPage();
},
'/auth/email_step': (BuildContext context) {
bootstrapMyappProviderInContext(context);
return const OBAuthEmailStepPage();
},
'/auth/username_step': (BuildContext context) {
bootstrapMyappProviderInContext(context);
return const OBAuthUsernameStepPage();
},
'/auth/password_step': (BuildContext context) {
bootstrapMyappProviderInContext(context);
return const OBAuthPasswordStepPage();
},
'/auth/submit_step': (BuildContext context) {
bootstrapMyappProviderInContext(context);
return const OBAuthSubmitPage();
},
'/auth/done_step': (BuildContext context) {
bootstrapMyappProviderInContext(context);
return const OBAuthDonePage();
},
'/auth/suggested_communities': (BuildContext context) {
bootstrapMyappProviderInContext(context);
return const OBSuggestedCommunitiesPage();
},
'/auth/login': (BuildContext context) {
bootstrapMyappProviderInContext(context);
return const OBAuthLoginPage();
},
'/auth/forgot_password_step': (BuildContext context) {
bootstrapMyappProviderInContext(context);
return const OBAuthForgotPasswordPage();
},
'/auth/verify_reset_password_link_step': (BuildContext context) {
bootstrapMyappProviderInContext(context);
return const OBAuthVerifyPasswordPage();
},
'/auth/set_new_password_step': (BuildContext context) {
bootstrapMyappProviderInContext(context);
return const OBAuthSetNewPasswordPage();
},
'/auth/password_reset_success_step': (BuildContext context) {
bootstrapMyappProviderInContext(context);
return const OBAuthPasswordResetSuccessPage();
},
'/waitlist/subscribe_email_step': (BuildContext context) {
bootstrapMyappProviderInContext(context);
return OBWaitlistSubscribePage();
},
'/waitlist/subscribe_done_step': (BuildContext context) {
bootstrapMyappProviderInContext(context);
WaitlistSubscribeArguments? args = ModalRoute.of(context)
?.settings
.arguments as WaitlistSubscribeArguments?;
return OBWaitlistSubscribeDoneStep(count: args?.count ?? 0);
}
}),
),
);
}
void bootstrapMyappProviderInContext(BuildContext context) {
// ignore: prefer_typing_uninitialized_variables
var myappprovider = MyappProvider.of(context);
var localizationservice = LocalizationService.of(context);
if (locale?.languageCode != localizationservice.getLocale().languageCode) {
Future.delayed(const Duration(milliseconds: 0), () {
MyApp.setLocale(context, locale);
});
}
myappprovider.setLocalizationService(localizationservice);
UniversalLinksService universalLinksService =
myappprovider.universalLinksService;
universalLinksService.digestLinksWithContext(context);
myappprovider.validationService
.setLocalizationService(localizationservice);
myappprovider.shareService.setContext(context);
}
}
// ignore: prefer_void_to_null
Future<Null> main() async {
MyApp app = MyApp();
// Run the whole app in a zone to capture all uncaught errors.
runZonedGuarded(() => runApp(app), (Object error, StackTrace stackTrace) {
if (isInDebugMode) {
print(error);
print(stackTrace);
print('In dev mode. Not sending report to Sentry.io.');
return;
}
SentryClient? sentryClient =
app.MyappProviderKey.currentState?.sentryClient;
try {
sentryClient?.captureException(
error,
stackTrace: stackTrace,
);
print('Error sent to sentry.io: $error');
} catch (e) {
print('Sending report to sentry.io failed: $e');
print('Original error: $error');
}
});
}
bool get isInDebugMode {
bool inDebugMode = false;
assert(inDebugMode = true);
return inDebugMode;
}
bool get isOnDesktop {
return Platform.isLinux || Platform.isMacOS || Platform.isWindows;
}
TextTheme _defaultTextTheme() {
// This text theme is merged with the default theme in the `TextData`
// constructor. This makes sure that the emoji font is used as fallback for
// every text that uses the default theme.
// ignore: prefer_typing_uninitialized_variables
var style;
if (isOnDesktop) {
style = const TextStyle(fontFamilyFallback: ['Emoji']);
}
return TextTheme(
bodyText2: style,
bodyText1: style,
button: style,
caption: style,
headline4: style,
headline3: style,
headline2: style,
headline1: style,
headline5: style,
overline: style,
subtitle1: style,
subtitle2: style,
headline6: style,
);
}
请协助,因为我已经花了太多时间试图解决这个问题。
我终于解决了上面的问题。对于任何读到这篇文章的人来说,都是一个错误的变量名(与类定义冲突(。
我更改了一个名为localization.dart的文件中的类名,该文件是从上面的Main.dart重新生成的。我所做的任何一个例子:
var MyProvider=MyProvider.of(context(;;
到
var myprovider=myprovider.of(context(;;
我认为这与变量名与类名冲突有关。