头图

在Sqlite数据库中有一列locale支持了多语言,所以只需要更改一下Sql查询条件就可以查出不同语言的数据。

image-20211010174334-jvp95ah.png

修改VegetableDao加入语言查询条件

[project_root]/lib/app/data/dao/vegetalbe_dao.dart

import 'package:floor/floor.dart';
import 'package:strapi_flutter_internation_poc/app/data/entity/vegetable.dart';

@dao
abstract class VegetableDao {
  @Query('SELECT * FROM vegetables_v WHERE  locale = :locale')
  Future<List<VegetableV>> findAll(String locale);
}

修改后重新运行Floor代码生成器

flutter packages pub run build_runner build

HomeController稍作调整

[project_root]/lib/app/modules/home/controllers/home_controller.dart

  Future<void> getAllVegetables() async {
    final result = await DbService.to.db.vegetableDao.findAll('en');
    vegetables.value = result;
  }

这样显示的数据就都是英文的了

image-20211010175216-r3ixc2x.png

接下来整合GetX的国际化特性

新建一个language_service

[project_root]/lib/app/common/services/language_service.dart

这里用到了get_storage做默认语言的缓存。记得要在Flutter项目中增加这个库的依赖。使用命令get install get_storage就可以快速的完成安装。

import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

class LanguageService extends GetxService {
  static LanguageService get to => Get.find();

  var box = GetStorage();
  var locale = Locale('en', 'US');
  var localeKey = 'en';

  Future<LanguageService> init() async {
    if (box.read('language') != null) {
      if (box.read('language') == 'zh-CN') {
        locale = Locale('zh', 'CN');
        localeKey = 'zh-CN';
      } else {
        locale = Locale('en', 'US');
        localeKey = 'en';
      }
    } else {
      if (ui.window.locale.languageCode == 'zh') {
        locale = Locale('zh', 'CN');
        localeKey = 'zh-CN';
      } else {
        locale = Locale('en', 'US');
        localeKey = 'en';
      }
    }

    return this;
  }

  void changeLocale(l) {
    if (l == Locale('zh', 'CN')) {
      localeKey = 'zh-CN';
      updateLocale(Locale('zh', 'CN'));
    } else if (l == Locale('en', 'US')) {
      localeKey = 'en';
      updateLocale(Locale('en', 'US'));
    }
    box.write('language', localeKey);
  }

  void updateLocale(_l) {
    locale = _l;
    Get.updateLocale(_l);
  }
}

GetX Cli 可以快速的通过JSON文件生成GetX框架所需要的多语言配置。

[project_root]/assets/locales下新建两个JSON文件

en_US.json

{
  "app": {
    "name": "VAF"
  },
  "locale": {
    "title": "Language",
    "zh": "中文",
    "en": "English"
  }
}

zh_CN.json

{
  "app": {
    "name": "蔬果"
  },
  "locale": {
    "title": "语言",
    "zh": "中文",
    "en": "English"
  }
}

运行命令

get generate locales assets/locales

可以得到[project_root]/lib/generated/locales.g.dart

class AppTranslation {
  static Map<String, Map<String, String>> translations = {
    'zh_CN': Locales.zh_CN,
    'en_US': Locales.en_US,
  };
}

class LocaleKeys {
  LocaleKeys._();
  static const app_name = 'app_name';
  static const locale_title = 'locale_title';
  static const locale_zh = 'locale_zh';
  static const locale_en = 'locale_en';
}

class Locales {
  static const zh_CN = {
    'app_name': '蔬果',
    'locale_title': '语言',
    'locale_zh': '中文',
    'locale_en': 'English',
  };
  static const en_US = {
    'app_name': 'VAF',
    'locale_title': 'Language',
    'locale_zh': '中文',
    'locale_en': 'English',
  };
}

在main.dart中增加对LanguageService的初始化

Future<void> initServices() async {
  print('starting services ...');
  await Get.putAsync(() => DbService().init());
  await Get.putAsync(() => LanguageService().init());
  print('All services started...');
}

修改runApp加入多语言配置

  runApp(
    GetMaterialApp(
      title: "Application",
      initialRoute: AppPages.INITIAL,
      getPages: AppPages.routes,
      translationsKeys: AppTranslation.translations,
      locale: LanguageService.to.locale,
      fallbackLocale: Locale('zh', 'CN'),
    ),
  );

调整Controller中的查询条件

final result = await DbService.to.db.vegetableDao.findAll('en');

改为

    final result = await DbService.to.db.vegetableDao
        .findAll(LanguageService.to.localeKey);

修改界面中的文字为引用多语言的资源

      appBar: AppBar(
        title: Text('Vegetables'),
        centerTitle: true,
      ),

改为

      appBar: AppBar(
        title: Text(LocaleKeys.app_name.tr),
        centerTitle: true,
      ),

再次运行就可以看到默认为中文的界面了

image-20211010182410-m6ayfcq.png

稍作完善再增加一个切换语言的按钮

appBar: AppBar(
        title: Text(LocaleKeys.app_name.tr),
        centerTitle: true,
        actions: [
          IconButton(
              onPressed: () {
                Get.dialog(SimpleDialog(
                  title: Text(LocaleKeys.locale_title.tr),
                  children: <Widget>[
                    SimpleDialogOption(
                      onPressed: () {
                        LanguageService.to.changeLocale(Locale('en', 'US'));
                      },
                      child: Padding(
                        padding: const EdgeInsets.symmetric(vertical: 6),
                        child: Text(LocaleKeys.locale_en.tr),
                      ),
                    ),
                    SimpleDialogOption(
                      onPressed: () {
                        LanguageService.to.changeLocale(Locale('zh', 'CN'));
                      },
                      child: Padding(
                        padding: const EdgeInsets.symmetric(vertical: 6),
                        child: Text(LocaleKeys.locale_zh.tr),
                      ),
                    ),
                  ],
                ));
              },
              icon: Icon(Icons.language))
        ],
      ),

非常便捷快速的就完成了语言的切换

image-20211010183432-nqf0vo3.png


nasawz
47 声望10 粉丝