[英]Dart & Flutter: How to call for a class method inside another class
[英]How to call get method inside class with dynamic index in flutter?
我在我的项目中采用了 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
),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.