flutter 国际化

2021-03-08  本文已影响0人  代瑶

https://flutterchina.club/tutorials/internationalization/
这个是中文flutter官网上的使用方法, 但是我并没用这种,自创了一种简单方法,记录下

创建一个region文件夹

lib文件夹下新建region文件夹.png
  1. chinese是中国文字
  2. english是国外的字

这里我们以中国市场为主, 当没有发现对应的english补充key时就用中文

import 'package:qgh/region/chinese/R.dart';
import 'package:qgh/region/english/R.dart';

class Region {
  static const ZH = "zh";
  static const EN = "en";

  static Region _instance;

  static Region get instance => _getInstance();

  static RChinese get R => _defR;
  static RChinese _defR;

  static Region _getInstance() {
    if (_instance == null) {
      _instance = Region._();
    }
    return _instance;
  }

  Region._() {
    ///init
  }

  factory Region() => _getInstance();

  static void initRegion(String local) {
    if (local == ZH) {
      Region._defR = RChinese();
    } else if (local == EN) {
      Region._defR = REnglish();
    } else {
      Region._defR = RChinese();
    }
  }
}

class RChinese {
  final String homeBarTitle = "首页";
}
import 'package:qgh/region/chinese/R.dart';

class REnglish extends RChinese { //这里是继承自中文字体,如果英文没有对应key,则用中文
  final homeBarTitle = "Home";
}
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    Region.initRegion(Region.ZH); //在程序初始化时,读取当前是中国还是外国

    return MaterialApp(
      title: Region.R.homeBarTitle, 
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: Region.R.homeBarTitle), //获取文字都这样来写
    );
  }
}
上一篇 下一篇

猜你喜欢

热点阅读