0

我在我的项目中采用 l10n 以在我的应用程序中支持多语言。

生成的 AppLocalizations 类包含多个获取翻译文本的方法。

我想以编程方式(或动态调用)在我的屏幕主体中调用这些 get 方法,我该怎么做?

生成的翻译飞镖

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!
    ),
  ),
),
4

1 回答 1

0

访问类实例的正确方法是:

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 
    ),
于 2021-07-19T16:01:36.317 回答