Flutter本地化插件best_naveen_localization的使用

发布于 1周前 作者 songsunli 来自 Flutter

Flutter本地化插件best_naveen_localization的使用

标题

Flutter本地化插件best_naveen_localization的使用

内容

Best naveen Localization flutter package for most common words used in mobile apps.

Flutter localization is the process of adapting your Flutter app to work with different languages, regions, and cultures. It you can create applications that can be used by people around the world by providing translations for text and content, as well as adapting other aspects like date and time formats, number formats, and more to suit the target audience.

示例代码

import 'package:best_naveen_localization/best_naveen_localization.dart';

void main() {
  /// 如果你想使用commonwords翻译,可以直接使用...许多更多的单词你可以搜索
  CommonTranslations.back;
  CommonTranslations.cancel;
  CommonTranslations.confirm;
  CommonTranslations.contactUs;
  CommonTranslations.yes;
  CommonTranslations.newMessages;
  CommonTranslations.next;
  CommonTranslations.changePassword;
  CommonTranslations.areYouSure;
  CommonTranslations.contact;
  CommonTranslations.location;

  /// 或者你可以像这样创建你的翻译
  final Map<String, Map<String, String>> translations = {
    'en': {'explore': 'Explore', 'profile': 'Profile', 'name': 'Name'},
    'fi': {'explore': 'Selaa', 'profile': 'Profiili', 'name': 'Nimi'},
    'ar': {'explore': 'استكشاف', 'profile': 'الملف الشخصي', 'name': 'اسم'}
  };

  /// 如果你想手动设置语言代码,请像这样分配
  GetLocale.langcode = 'en';

  GetTranslate.translations = translations;

  String profile = GetTranslate.getTranslation('profile');
  String explore = GetTranslate.getTranslation('explore');
  String name = GetTranslate.getTranslation('name');

  print(profile);
  print(explore);
  print(name);
}

使用说明

  1. 首先,在 pubspec.yaml 文件中添加 best_naveen_localization 依赖项。

    dependencies:
      flutter:
        sdk: flutter
      best_naveen_localization:
    
  2. 在需要使用的包的地方导入 best_naveen_localization 包。

    import 'package:best_naveen_localization/best_naveen_localization.dart';
    
  3. 使用 CommonTranslations 类中的方法来获取翻译。例如:

    String settings = CommonTranslations.settings;
    String chats = CommonTranslations.chats;
    String help = CommonTranslations.help;
    String account = CommonTranslations.account;
    String save = CommonTranslations.save;
    String search = CommonTranslations.search;
    String accountCreatedSuccessfully = CommonTranslations.accountCreatedSuccessfully;
    String accountDeletedSuccessfully = CommonTranslations.accountDeletedSuccessfully;
    String createAccount = CommonTranslations.createAccount;
    String currentLocation = CommonTranslations.currentLocation;
    
  4. 如果你想要自定义翻译,可以创建一个映射表来存储不同语言的翻译内容。

    final Map<String, Map<String, String>> translations = {
      'en': {'explore': 'Explore', 'profile': 'Profile', 'name': 'Name'},
      'fi': {'explore': 'Selaa', 'profile': 'Profiili', 'name': 'Nimi'},
      'ar': {'explore': 'استكشاف', 'profile': 'الملف الشخصي', 'name': 'اسم'}
    };
    
  5. 设置默认的语言代码。

    GetLocale.langcode = 'en';
    
  6. 将翻译映射表赋值给 GetTranslate.translations

    GetTranslate.translations = translations;
    
  7. 获取翻译内容。

    String profile = GetTranslate.getTranslation('profile');
    String explore = GetTranslate.getTranslation('explore');
    String name = GetTranslate.getTranslation('name');
    
  8. 打印翻译结果。

    print(profile);
    print(explore);
    print(name);
    

更多关于Flutter本地化插件best_naveen_localization的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter本地化插件best_naveen_localization的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是关于如何在Flutter项目中使用best_naveen_localization插件来实现本地化的代码示例。这个插件可以帮助你轻松地在Flutter应用中实现多语言支持。

1. 添加依赖

首先,你需要在pubspec.yaml文件中添加best_naveen_localization依赖:

dependencies:
  flutter:
    sdk: flutter
  best_naveen_localization: ^最新版本号  # 请替换为实际可用的最新版本号

然后运行flutter pub get来安装依赖。

2. 创建语言资源文件

在你的项目根目录下创建一个assets/locales文件夹,并在其中创建不同语言的JSON文件。例如:

  • assets/locales/en.json
  • assets/locales/zh.json

en.json内容示例:

{
  "welcome_message": "Welcome to our app",
  "goodbye_message": "Goodbye"
}

zh.json内容示例:

{
  "welcome_message": "欢迎来到我们的应用",
  "goodbye_message": "再见"
}

3. 配置pubspec.yaml以包含语言资源

pubspec.yaml文件中添加对语言资源文件的引用:

flutter:
  assets:
    - assets/locales/en.json
    - assets/locales/zh.json

4. 初始化本地化插件

在你的主文件(例如main.dart)中,初始化BestNaveenLocalization

import 'package:flutter/material.dart';
import 'package:best_naveen_localization/best_naveen_localization.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Localization Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      localizationsDelegates: [
        BestNaveenLocalization.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
      supportedLocales: [
        Locale('en', ''),
        Locale('zh', ''),
      ],
      locale: Locale('en'), // 初始语言
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  BestNaveenLocalization bestNaveenLocalization;

  @override
  Widget build(BuildContext context) {
    bestNaveenLocalization = BestNaveenLocalization.of(context);

    return Scaffold(
      appBar: AppBar(
        title: Text(bestNaveenLocalization.translate('welcome_message')),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(bestNaveenLocalization.translate('welcome_message')),
            ElevatedButton(
              onPressed: () {
                // 切换语言示例
                setState(() {
                  if (Localizations.localeOf(context).languageCode == 'en') {
                    BestNaveenLocalization.setLocale(context, Locale('zh'));
                  } else {
                    BestNaveenLocalization.setLocale(context, Locale('en'));
                  }
                });
              },
              child: Text('Switch Language'),
            ),
            Text(bestNaveenLocalization.translate('goodbye_message')),
          ],
        ),
      ),
    );
  }
}

5. 加载语言资源

main.dart或你的应用初始化代码中,确保加载语言资源:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await BestNaveenLocalization.load(context: null, 
    path: 'assets/locales', 
    defaultLocale: Locale('en'));
  runApp(MyApp());
}

注意:BestNaveenLocalization.loadcontext参数在初始化时可能为null,因为contextmain函数中尚未创建。

总结

以上代码展示了如何在Flutter项目中使用best_naveen_localization插件来实现本地化。通过创建语言资源文件、配置pubspec.yaml、初始化插件以及构建UI,你可以轻松地在你的应用中支持多语言。希望这个示例能帮到你!

回到顶部