我在项目中采用了l10n,以在我的应用程序中支持多语言。
生成的AppLocalizations类包含翻译文本的多个get方法。
我想在屏幕主体中以编程方式(或动态调用(调用这些get方法,我该怎么做?
生成的翻译Dart
import 'translate.dart';
/// The translations for English (`en`).
class AppLocalizationsEn extends AppLocalizations {
AppLocalizationsEn([String locale = 'en']) : super(locale);
@override
String get splashPageViewTitle1 => 'Welcome!';
@override
String get splashPageViewTitle2 => 'Let's go';
@override
String get splashPageViewTitle3 => 'Byebye';
}
生成前
List splashData = [
{
"textCode": "splashPageViewTitle1",
"image": "assets/images/splash_1.png"
},
{
"textCode": "splashPageViewTitle2",
"image": "assets/images/splash_2.png"
},
{
"textCode": "splashPageViewTitle3",
"image": "assets/images/splash_3.png"
},
];
内部构建
Expanded(
flex: 3,
child: PageView.builder(
onPageChanged: (value) {
setState((){
currentPage = value;
});
},
itemCount: splashData.length,
itemBuilder: (context, index) => SplashContent(
image: splashData[index]["image"],
//text: splashData[index]["text"]
text: AppLocalizations.of(context)!.['splashPageViewTitle'+index] //<<<<<<<<<<<<<Failed in here!
),
),
),
访问类实例的正确方法是:
AppLocalizations.of(context)!.splashPageViewTitle1
但当你试图根据索引访问时,你可以创建一个单独的函数:
String title(int index) {
if(index == 1) {
return AppLocalizations.of(context)!.splashPageViewTitle1;
} else if(index == 2) {
return AppLocalizations.of(context)!.splashPageViewTitle2;
} else if(index == 3){
return AppLocalizations.of(context)!.splashPageViewTitle3;
}
}
并在你的itemBuilder
上使用它,如下所示:
itemBuilder: (context, index) => SplashContent(
image: splashData[index]["image"],
//text: splashData[index]["text"]
text: title(index), //// <----- here
),