美文网首页
Flutter项目国际化(本地化,全球化,多语言)

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

作者: 蓝不蓝编程 | 来源:发表于2023-01-25 14:42 被阅读0次

    目标

    在Flutter项目中实现国际化,支持多种语言。


    image

    开发工具

    下载IntelliJ IDEA

    安装插件:Flutter Intl

    安装完成后重启IDE。


    image

    使用Intl对项目进行初始化

    image

    添加语言

    image
    image
    image

    添加内容

    image
    image

    修改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 | 小程序 | 鸿蒙
    公众号:蓝不蓝编程

    相关文章

      网友评论

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

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