美文网首页
使用flutter pub包 easy_localization

使用flutter pub包 easy_localization

作者: 君幸食j | 来源:发表于2022-03-30 11:27 被阅读0次

1.用终端在桌面创建flutter项目 use_easy_localization 并导入pub包

flutter create use_easy_localization

flutter pub add easy_localization 

2.新建resources/langs文件夹,加入语言配置json文件,配置中英文两种语言。

en.json

{
    "title": "HelloWorld",
    "content": {
        "message": "HelloWorld,HelloWorld,HelloWorld"
    }
}

en-US.json

{
    "title": "HelloWorld",
    "content": {
        "message": "HelloWorld,HelloWorld,HelloWorld"
    }
}

zh.json

{
    "title": "世界",
    "content": {
        "message": "世界,世界,世界"
    }
}

zh-CH.json

{
    "title": "世界",
    "content": {
        "message": "世界,世界,世界"
    }
}

3.在 pubspec.yal 配置资源路径

flutter:
  assets:
    - resources/langs/
    

4.在 ios/Runner/Info.plist 添加key

  <key>CFBundleLocalizations</key>
    <array>
        <string>en</string>
        <string>zh</string>
    </array> 

5.添加 EasyLocalization 组件

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await EasyLocalization.ensureInitialized();

  runApp(
    EasyLocalization(
      child: const MyApp(),
      supportedLocales: const [
        Locale('en', 'US'),
        Locale('zh', 'CH'),
      ],
      path: 'resources/langs',
      assetLoader: const CodegenLoader(),
    ),
  );
}
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: context.localizationDelegates,
      supportedLocales: context.supportedLocales,
      locale: context.locale,
      title: '多语言',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: '多语言'),
    );
  }
}

6.切换语言

/// 切换语言
  void _changeLocale() async {
    if (context.locale.toString() == 'zh_CH') {
      await context.setLocale(context.supportedLocales[0]);
    } else {
      await context.setLocale(context.supportedLocales[1]);
    }
  }

7.完整代码

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:use_easy_localization/generated/locale_keys.g.dart';

import 'generated/codegen_loader.g.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await EasyLocalization.ensureInitialized();

  runApp(
    EasyLocalization(
      child: const MyApp(),
      supportedLocales: const [
        Locale('en', 'US'),
        Locale('zh', 'CH'),
      ],
      path: 'resources/langs',
      assetLoader: const CodegenLoader(),
    ),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: context.localizationDelegates,
      supportedLocales: context.supportedLocales,
      locale: context.locale,
      title: '多语言',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: '多语言'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  /// 切换语言
  void _changeLocale() async {
    if (context.locale.toString() == 'zh_CH') {
      await context.setLocale(context.supportedLocales[0]);
    } else {
      await context.setLocale(context.supportedLocales[1]);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(LocaleKeys.title).tr(),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              LocaleKeys.content.tr(gender: "message"),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _changeLocale,
        tooltip: '切换语言',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Github代码

相关文章

网友评论

      本文标题:使用flutter pub包 easy_localization

      本文链接:https://www.haomeiwen.com/subject/rabijrtx.html