Flutter项目国际化(本地化,全球化,多语言)

时间:2023-01-26 15:00:57

目标

在Flutter项目中实现国际化,支持多种语言。 Flutter项目国际化(本地化,全球化,多语言)

开发工具

下载IntelliJ IDEA

安装插件:Flutter Intl

安装完成后重启IDE。 Flutter项目国际化(本地化,全球化,多语言)

使用Intl对项目进行初始化

Flutter项目国际化(本地化,全球化,多语言)

添加语言

Flutter项目国际化(本地化,全球化,多语言)Flutter项目国际化(本地化,全球化,多语言)Flutter项目国际化(本地化,全球化,多语言)

添加内容

Flutter项目国际化(本地化,全球化,多语言)Flutter项目国际化(本地化,全球化,多语言)

修改pubspec.yaml

dependencies:
  flutter:
    sdk: flutter

修改为:

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter

调用

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'generated/l10n.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      supportedLocales: S.delegate.supportedLocales,
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
        S.delegate
      ],
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              S.of(context).app_name,
            ),
          ],
        ),
      ),
    );
  }
}

关键代码:

import 'package:flutter_localizations/flutter_localizations.dart';
import 'generated/l10n.dart';
S.of(context).app_name

完整代码参考样例

https://gitee.com/lblbc/notepad-multi-lang

关于

厦门大学计算机专业|华为八年高级工程师
专注《零基础学编程系列》 http://lblbc.cn/blog
包含:Java | 安卓 | 前端 | Flutter | iOS | 小程序 | 鸿蒙
公众号:蓝不蓝编程