错误:延迟初始化错误:字段"共享首选项"尚未初始化。Flutter Verygoodcli web app



初始化已延迟的变量时出错

在我的应用程序中,有一个composition_root.dart文件组成了所有页面。我正在使用verygoodcli应用程序使用verygoodsanalysis将代码迁移到Flutter2.10

这是Composition根:


class CompositionRoot {
static late SharedPreferences _sharedPreferences;
static late ILocalStore _localStore;
static late String _baseUrl;
static late Client _client;
static void configure() {
_localStore = LocalStore(_sharedPreferences);
_client = Client();
_baseUrl = 'http://localhost:3000';
}
static Widget composeAuthUI() {
final IAuthApi _api = AuthApi(_baseUrl, _client);
final _manager = AuthManager(_api);
final _authCubit = AuthstateCubit(_localStore);
final _signUpService = SignUpService(_api);
return BlocProvider(
create: (BuildContext context) => _authCubit,
child: AuthPage(_manager, _signUpService),
);
}
}

然而,当我运行代码时,我似乎得到了以下错误消息:


Error: LateInitializationError: Field 'sharedPreferences' has not been
initialized.
at Object.throw_ [as throw] (http://localhost:40837/dart_sdk.js:5067:11)
at Function.get sharedPreferences [as sharedPreferences]
(http://localhost:40837/packages/verygoodapp/composition_root.dart.lib.js:58
:37)
at Function.configure
(http://localhost:40837/packages/verygoodapp/composition_root.dart.lib.js:88
:118)
at main
(http://localhost:40837/packages/verygoodapp/main_development.dart.lib.js:45
:38)
at main (http://localhost:40837/web_entrypoint.dart.lib.js:36:29)
at main.next (<anonymous>)

我该如何调试这个错误?你介意解释一下发生了什么吗?我似乎不明白。在编写UI之前,会在main_*.dart文件中配置应用程序。

main_*.dart


void main() {
CompositionRoot.configure();
bootstrap(() => const App());
}

我们的应用程序小工具类:

class App extends StatelessWidget {
const App({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
appBarTheme: const AppBarTheme(color: Color(0xFF13B9FF)),
colorScheme: ColorScheme.fromSwatch(
accentColor: const Color.fromARGB(255, 190, 27, 27),
),
),
debugShowCheckedModeBanner: false,
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
home: CompositionRoot.composeAuthUI(),
);
}
}

我好像听不懂,请帮帮我。提前谢谢。

_sharedPreferences尚未初始化。这意味着它没有存储任何内容,而您正试图使用它

试试这个

_sharedPreferences = await SharedPreferences.getInstance();
_localStore = LocalStore(_sharedPreferences);

那么你就可以去了

正如takudzw-m回答的那样,我能够以这种方式实例化sharedPreferences。


/// This is an async method that instantiates
/// and configures the static variables and
/// should not but returns void.
// ignore: avoid_void_async
static void configure() async {
_sharedPreferences = await SharedPreferences.getInstance();
_localStore = LocalStore(_sharedPreferences);
_client = Client();
_baseUrl = 'http://localhost:3000';
}

感谢StackOverflow社区。

最新更新