访问在 MaterialApp 之上使用多提供程序定义的服务中的本地化



当这些服务是在位于 MaterialApp 之上的多提供程序中定义的时,我如何访问服务中的本地化(翻译(?

现在我收到"错误:在此_DefaultInheritedProviderScope<上方找不到正确的提供程序......等等。>

这是有道理的,但我希望我的整个应用程序都可以访问这些服务,因此它们必须位于 MaterialApp 之上。

class MyApp extends StatelessWidget {
MyApp({
this.isZebra,
this.scanWithCamera,
});
final bool isZebra;
final bool scanWithCamera;
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: providers(isZebra: isZebra, scanWithCamera: scanWithCamera),
child: Builder(
builder: (BuildContext context) => MaterialApp(
localizationsDelegates: [
S.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: S.delegate.supportedLocales,
theme: companyTheme(context),
onGenerateTitle: (context) => S.of(context).title,
navigatorObservers: [
Provider.of<RouteObserver>(
context,
listen: false,
),
],
home: S005StartupPage(),
),
),
);
}
}

我最终将多提供程序移动到MaterialApp的构建器方法。这基本上是我问题的答案。

不幸的是,RouteObserver 必须保持在 MaterialApp 之上,因为它需要传递给 MaterialApp 的 navigatorObserver 参数。

现在可以访问翻译服务中的翻译代码 [S.of(_context(],以便其他服务可以使用翻译。

class MyApp extends StatelessWidget {
MyApp({
this.isZebra,
this.scanWithCamera,
});
final bool isZebra;
final bool scanWithCamera;
@override
Widget build(BuildContext context) {
return Provider<RouteObserver>(
create: (_) => RouteObserver(),
child: Builder(builder: (context) {
return MaterialApp(
builder: (context, child) => MultiProvider(
providers: providers(
isZebra: isZebra,
scanWithCamera: scanWithCamera,
),
child: child,
),
localizationsDelegates: [
S.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: S.delegate.supportedLocales,
theme: companyTheme(context),
onGenerateTitle: (context) => S.of(context).title,
navigatorObservers: [
Provider.of<RouteObserver>(
context,
listen: false,
),
],
home: S005StartupPage(),
);
}),
);
}
}

最新更新