Flutter all-rounder GetX - multilingual configuration/theme setting/offline cache

Use 

 Principles

1. Multilingual configuration

First create a new Messages class to inherit Translations

class Messages extends Translations {
  @override
  Map<String, Map<String, String>> get keys => {
        "en_US": {
         Globalization.english: "english",
       
        },
        "zh_CN": {
         Globalization.english: "英语",
     
        }
      };
}


Then declare a constant class to store the key for easy reference

class Globalization {
  static const String english = "english";
  
}

Then configure it in GetMaterialApp
 

GetMaterialApp(
      translations: Messages(),
      locale: const Locale('zh', 'CN'),
        fallbackLocale: Locale('en', 'US')
          ...
    );


The translations input is the object of the class we defined that inherits from Translations, the locale is the language we use by default, and the fallbackLocale is the resource configured by fallbackLocale when our default language resources are not available.

The best step is to use it. As follows:

Text(Globalization.english.tr);

If you want to get the system locale you can use the following

return GetMaterialApp(
    locale: Get.deviceLocale,
);

If you want to change the locale you can set it as follows

var locale = Locale('en', 'US');
Get.updateLocale(locale);


2. Offline storage


GetX can cache content objects to share data between different pages. When using it, you need to pay attention to the put operation and then the find operation, otherwise an exception will be thrown.

The first is the memory cache

Get.put(CacheData(name: '这是缓存数据'));
CacheData cache = Get.find();


GetX provides a get_storage plug-in for offline storage. Compared with shared_preferences, its advantage is that it is written in pure Dart and does not depend on native, so it can be used on multiple platforms such as Android, iOS, Web, Linux, and Mac. GetStorage is based on memory and file storage. When there is data in the memory container, it is read from memory first. At the same time, when constructing the GetStorage object, specify the stored file name and the container for storing the data.

GetStorage storage = GetStorage();
storage.write('name', 'river');
storage.read('name');


3. Theme settings
 

Set to light theme Get.changeTheme(ThemeData.light());
Set to dark theme Get.changeTheme(ThemeData.dark());
 
Put it in an onPressed, judge according to Get.isDarkMode

Get.changeTheme(Get.isDarkMode? ThemeData.light(): ThemeData.dark());

 GetMaterialApp中设置默认主题
 GetMaterialApp(
    theme:  ThemeData.light(),
    darkTheme: ThemeData.dark(),
    themeMode: ThemeMode.light
)


 

Guess you like

Origin blog.csdn.net/hjjdehao/article/details/126492262