Internationalization configuration
When we use the MaterialApp of the system to realize the internationalization configuration, we need to do a lot of configuration, and also need to manually rely on the third party components, while using GetX to realize the internationalization configuration, you only need one line of code to realize the switch, next we will look at the specific implementation.
Video Tutorial Address
Zero basic video tutorial address
Step 1: Application entry configuration
- Translations: Internationalization configuration files
- Locale: Sets the default language. If this parameter is not set, the current language is used
- FallbackLocale: the language used when the configuration is incorrect
import 'package:flutter/material.dart';
import 'package:flutter_getx_example/InternationalizationExample/InternationalizationExample.dart';
import 'package:get/get.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
/// Internationalization configuration
return GetMaterialApp(
title: "GetX",
translations: Messages(),
locale: Locale('zh'.'CN'), // Set the default language
fallbackLocale: Locale("zh"."CN"), // The language to use in case of a configuration errorhome: InternationalizationExample(), ); }}Copy the code
Step 2: Create the internationalization class
You need to inherit the keys method from Translations and override it.
import 'package:get/get.dart';
class Messages extends Translations {
@override
// TODO: implement keys
Map<String.Map<String.String>> get keys => {
'zh_CN': {
'hello': "Hello world."
},
'en_US': {
'hello': 'hello world'}}; }Copy the code
Step 3: Create a controller class for switching languages
import 'dart:ui';
import 'package:get/get.dart';
class MessagesController extends GetxController {
void changeLanguage(String languageCode, String countryCode) {
varlocale = Locale(languageCode, countryCode); Get.updateLocale(locale); }}Copy the code
Step 4: Instantiate the controller and use it
import 'package:flutter/material.dart';
import 'package:flutter_getx_example/GetXControllerWorkersExample/WorkersConroller.dart';
import 'package:flutter_getx_example/InternationalizationExample/MessagesCnotroller.dart';
import 'package:get/get.dart';
class InternationalizationExample extends StatelessWidget {
MessagesController messagesController = Get.put(MessagesController());
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Internationalization"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text('hello'.tr, style: TextStyle(color: Colors.pink, fontSize: 30)),
ElevatedButton(
onPressed: () => messagesController.changeLanguage('zh'."CN"),
child: Text("Switch to Chinese")
),
SizedBox(height: 20,),
ElevatedButton(
onPressed: () => messagesController.changeLanguage('en'."US"),
child: Text("Switch to English"() [() [() [() [() }}Copy the code
Results show
Dependency injection
In previous articles, we often used get.put (MyController()) to create controller instances, so that we can create controller instances without using them. GetX also provides a number of methods for creating instances, depending on your business
- Get.put() : Instances can be created without using the controller
- Get.lazyput () : creates instances in lazy loading mode and only when used
- Get. PutAsync () :
Get.put()
Asynchronous version of the - Get.create() : a new instance is created each time it is used
Let’s take a look at the code demo
Step 1: Application entry configuration
import 'package:flutter/material.dart';
import 'package:flutter_getx_example/DependecyInjectionExample/DependecyInjectionExample.dart';
import 'package:get/get.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GetMaterialApp(
title: "GetX", home: DependecyInjectionExample(), ); }}Copy the code
Step 2: Create a controller
import 'package:flutter_getx_example/ObxCustomClassExample/Teacher.dart';
import 'package:get/get.dart';
class MyController extends GetxController {
var teacher = Teacher();
voidconvertToUpperCase() { teacher.name.value = teacher.name.value.toUpperCase(); }}Copy the code
Step 3: Instantiate the controller and use it
import 'package:flutter/material.dart';
import 'package:flutter_getx_example/GetXControllerExample/MyController.dart';
import 'package:get/get.dart';
class DependecyInjectionExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
// The instance will be created even if the controller is not used
// Tag will be used to find instances with tag names
// The controller is processed when not in use, but if permanently true, the instance remains active throughout the application
MyController myController = Get.put(MyController(), permanent: true);
// MyController myController = Get.put(MyController(), tag: "instancel", permanent: true);
// The instance will be created at usage time
// It is similar to 'permanent', except that the instance is discarded when not in use
// But when it is needed again, get recreates the instance
// Get.lazyPut(()=> MyController());
// Get.lazyPut(()=> MyController(), tag: "instancel");
// Get. Put Asynchronous version
// Get.putAsync
(() async => await MyController());
// A new instance is returned each time
// Get.create<MyController>(() => MyController());
return Scaffold(
appBar: AppBar(
title: Text("GetXController"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
// The instance is created using a tag
// Get.find<MyController>(tag: 'instancel');
Get.find<MyController>();
},
child: Text("Don't light me."() [(), (), (); }}Copy the code
Get Service
This class is like a GetxController that shares the same lifecycle onInit(), onReady(), onClose(). But there’s no logic in it. It simply informs GetX’s dependency injection system that the subclass cannot be removed from memory. So if you need to absolutely persist a class instance over the lifetime of your application, then GetxService is the place to use it.
Step 1: Create the Service
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
class Service extends GetxService {
Future<void> getCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
int count = (prefs.getInt("counter")??0) + 1;
print("Count has the value:$count");
await prefs.setInt("counter", count); }}Copy the code
Step 2: Initialize the Service
import 'package:flutter/material.dart';
import 'package:flutter_getx_example/GetXServiceExample/GetXServiceExample.dart';
import 'package:flutter_getx_example/GetXServiceExample/Service.dart';
import 'package:get/get.dart';
/// Initializing the service
Future<void> main() async {
await initServices();
runApp(MyApp());
}
Future<void> initServices() async {
print("Initialize the service");
await Get.putAsync(() async= >await Service());
print("All Services started");
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GetMaterialApp(
title: "GetX", home: GetXServiceExample(), ); }}Copy the code
Step 3: Call the Service
import 'package:flutter/material.dart';
import 'package:flutter_getx_example/GetXServiceExample/Service.dart';
import 'package:get/get.dart';
class GetXServiceExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("GetX Service"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
Get.find<Service>().getCounter();
},
child: Text("Click and I add one."() [(), (), (); }}Copy the code
GetX Binding
When we use the GetX state manager, every time is often with the need to manually instantiate a controller, so the basic page needs to be instantiated once, so you too much trouble, and the Binding can solve the above problems, can be in the project initialization time all need to undertake unity of state management controller initialization, Here’s a code demo:
Step 1: Declare the controller class you want to bind
import 'package:flutter_getx_example/GetXBindingExample/controller/BindingHomeController.dart';
import 'package:flutter_getx_example/GetXBindingExample/controller/BindingMyController.dart';
import 'package:get/get.dart';
class AllControllerBinding implements Bindings {
@override
void dependencies() {
// TODO: implement dependenciesGet.lazyPut<BindingMyController>(() => BindingMyController()); Get.lazyPut<BindingHomeController>(() => BindingHomeController()); }}import 'package:get/get.dart';
class BindingHomeController extends GetxController {
var count = 0.obs;
voidincrement() { count++; }}import 'package:get/get.dart';
class BindingMyController extends GetxController {
var count = 0.obs;
voidincrement() { count++; }}Copy the code
Step 2: Initialize the binding at project startup
There are many ways to bind, and there are different ways to use it in different situations. Here is one of them. If you need more details, watching videos is the best choice.
import 'package:flutter/material.dart';
import 'package:flutter_getx_example/GetXBindingExample/binding/AllControllerBinding.dart';
import 'package:flutter_getx_example/GetXBindingExample/GetXBindingExample.dart';
import 'package:get/get.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
/// GetX Binding
return GetMaterialApp(
title: "GetX", initialBinding: AllControllerBinding(), home: GetXBindingExample(), ); }}Copy the code
Step 3: Use the state manager on the page
import 'package:flutter/material.dart';
import 'package:flutter_getx_example/GetXBindingExample/BHome.dart';
import 'package:flutter_getx_example/GetXBindingExample/binding/BHomeControllerBinding.dart';
import 'package:flutter_getx_example/GetXBindingExample/controller/BindingMyController.dart';
import 'package:get/get.dart';
class GetXBindingExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("GetXBinding"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Obx(() => Text(
"The value of the counter is${Get.find<BindingMyController>().count}",
style: TextStyle(color: Colors.red, fontSize: 30),
)),
SizedBox(height: 20,),
ElevatedButton(
onPressed: () {
Get.find<BindingMyController>().increment();
},
child: Text("Click plus 1")
),
SizedBox(height: 20,),
ElevatedButton(
onPressed: () {
Get.to(BHome());
// Get.toNamed("/bHome");
// Get.to(BHome(), binding: BHomeControllerBinding());
},
child: Text("Go to home page"() [() [() [() [() }}Copy the code