[英]How to call get method inside class with dynamic index in flutter?
I adopt l10n into my project to support multilingual in my app.我在我的项目中采用了 l10n 以在我的应用程序中支持多语言。
The generated AppLocalizations classes contains multiple get method for the translated text.生成的 AppLocalizations 类包含多个用于翻译文本的 get 方法。
I want to programmatically(or called dynamically) call these get method in my screen body, how can I do that?我想以编程方式(或动态调用)在我的屏幕主体中调用这些 get 方法,我该怎么做?
Generated Translate Dart生成的翻译 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';
}
Before Build构建前
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"
},
];
Inside Build内部构建
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!
),
),
),
The correct way to access the class instance is:访问类实例的正确方法是:
AppLocalizations.of(context)!.splashPageViewTitle1
But as you are trying to access depending on the index you can create a separate function:但是当您尝试根据索引进行访问时,您可以创建一个单独的函数:
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;
}
}
And use it on your itemBuilder
like this:并在您的
itemBuilder
上使用它,如下所示:
itemBuilder: (context, index) => SplashContent(
image: splashData[index]["image"],
//text: splashData[index]["text"]
text: title(index), //// <----- here
),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.