我是Flutter的新手,所以我不確定我的思路是否有意義。我目前正在使用一個名為EasyLocalization的包來本地化我的應用程式。在這樣做的程序中,我試圖參考我的應用程式的當前位置,該位置由 EasyLocalization 在一個完全獨立于 widgets 的服務類中設定,但該包提供的唯一方法是參考背景關系
。在他們的例子中,下面的代碼可以作業
print(context.locale.toString())。
然而,由于我希望在一個不使用部件的 "服務 "類中獲得該值,我根本無法呼叫任何背景關系。因此,像這樣的代碼在我的widget上可以使用,但在獨立的服務類中卻不能使用,因為那里不存在背景關系
。var currentLocale = EasyLocalization.of(context)?.locale ? 'en'。
我還嘗試了一些其他的代碼來獲得本地化,但它們與我的應用程式同步的實際本地化結果不同。例如,當我的應用程式在EasyLocalization中以'zh'運行時,其他的方法,如下面的方法只能回傳'en-US'
。print( Intl().locale)。
print(Intl.getCurrentLocale() )。
我讓它部分作業的一個方法是在我的小組件中創建一個函式,當點擊時設定一個全域值,然后參考該值,但這感覺很 "黑",而且不足以滿足我的用例,即資料在應用程式啟動時被加載,然后通過使用背景關系區域設定的翻譯函式。大多數其他搜索結果也只顯示了導航和工具列的資訊,這似乎對我的使用情況沒有幫助,所以我目前沒有想法,只能向 SO 尋求幫助。
下面是我的MaterialApp(),如果有幫助的話
。Widget build(BuildContext context) {
return ProviderScope(
孩子。MaterialApp(
localizationsDelegates: context.localizationDelegates,
supportedLocales: context.supportedLocales,
locale: context.locale,
debugShowCheckedModeBanner。false。
// Todo: 實作黑暗模式的顏色主題
theme: lightTheme,
onGenerateRoute: AppRouter.generateRoutes,
));
}
uj5u.com熱心網友回復:
你可以使用導航器鍵來從任何地方訪問當前的背景關系。你必須創建全域密鑰并將其傳遞給材料應用。
//create key。
final navigatorKey = new GlobalKey<NavigatorState>()。
/pass it to material app
Widget build(BuildContext context) {
return ProviderScope(
孩子。MaterialApp(
navigatorKey: navigatorKey, //key
localizationsDelegates: context.localizationDelegates,
supportedLocales: context.supportedLocales,
locale: context.locale,
debugShowCheckedModeBanner。false。
// Todo: 實作黑暗模式的顏色主題
theme: lightTheme,
onGenerateRoute: AppRouter.generateRoutes,
));
}
//訪問背景關系。
print(navigatorKey.currentContext.locale.toString())。
uj5u.com熱心網友回復:
你的服務類在設計上應該是獨立于地域的,所以把locale作為一個輸入,例如:
class I18nService {
final String locale;
I18nService(this.locale)。
String sayHello() {
if (locale == 'en_CA'/span>) {
return 'hello Canada';
}
return 'hello world';
}
我還建議研究一下provider包,你可以使用ProxyProvider實體化你的服務,并在那里傳入locale。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/313089.html
標籤:
上一篇:attr/selectableItemBackgroundBorderless在工具條內的ImageView中不起作用。
