Flutter GetX系列教程---國(guó)際化配置、依賴注入、Binding

國(guó)際化配置

在我們使用系統(tǒng)自帶MaterialApp來(lái)實(shí)現(xiàn)國(guó)際化配置,需要進(jìn)行很多配置,而且還需要手動(dòng)去依賴第三方組件,而使用GetX來(lái)實(shí)現(xiàn)國(guó)際化配置,你只需要一行代碼即可實(shí)現(xiàn)切換,接下來(lái)我們看一下具體實(shí)現(xiàn)。

視頻教程地址

零基礎(chǔ)視頻教程地址

第一步:應(yīng)用程序入口配置

  • translations: 國(guó)際化配置文件
  • locale: 設(shè)置默認(rèn)語(yǔ)言,不設(shè)置的話為系統(tǒng)當(dāng)前語(yǔ)言
  • fallbackLocale: 配置錯(cuò)誤的情況下,使用的語(yǔ)言
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) {
    /// 國(guó)際化配置
    return GetMaterialApp(
      title: "GetX",
      translations: Messages(),
      locale: Locale('zh', 'CN'), //設(shè)置默認(rèn)語(yǔ)言
      fallbackLocale: Locale("zh", "CN"), // 在配置錯(cuò)誤的情況下,使用的語(yǔ)言
      home: InternationalizationExample(),
    );
  }
}

第二步:創(chuàng)建國(guó)際化類

需要繼承自Translations并重寫(xiě)keys方法。

import 'package:get/get.dart';

class Messages extends Translations {

  @override
  // TODO: implement keys
  Map<String, Map<String, String>> get keys => {
    'zh_CN': {
      'hello': "你好, 世界"
    },
    'en_US': {
      'hello': 'hello world'
    }
  };
}

第三步:創(chuàng)建控制器類,用于切換語(yǔ)言

import 'dart:ui';
import 'package:get/get.dart';

class MessagesController extends GetxController {

  void changeLanguage(String languageCode, String  countryCode) {
    var locale = Locale(languageCode, countryCode);
    Get.updateLocale(locale);
  }
}

第四步:實(shí)例化控制器并使用


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("切換到中文")
            ),
            SizedBox(height: 20,),
            ElevatedButton(
              onPressed: () => messagesController.changeLanguage('en', "US"),
              child: Text("切換到英文")
            ),
          ],
        ),
      ),
    );
  }
}

效果展示

image

依賴注入

在前面的文章中,我們經(jīng)常使用Get.put(MyController())來(lái)進(jìn)行控制器實(shí)例的創(chuàng)建,這樣我們就算不使用控制器實(shí)例也會(huì)被創(chuàng)建,其實(shí)GetX還提供很多創(chuàng)建實(shí)例的方法,可根據(jù)不同的業(yè)務(wù)來(lái)進(jìn)行創(chuàng)建,接下來(lái)我們簡(jiǎn)單介紹一下幾個(gè)最常用的

  • Get.put(): 不使用控制器實(shí)例也會(huì)被創(chuàng)建
  • Get.lazyPut(): 懶加載方式創(chuàng)建實(shí)例,只有在使用時(shí)才創(chuàng)建
  • Get.putAsync<T>(): Get.put()的異步版版本
  • Get.create<T>(): 每次使用都會(huì)創(chuàng)建一個(gè)新的實(shí)例

我們來(lái)看一下代碼演示

第一步:應(yīng)用程序入口配置

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(),
    );
  }
}

第二步:創(chuàng)建控制器

import 'package:flutter_getx_example/ObxCustomClassExample/Teacher.dart';
import 'package:get/get.dart';

class MyController extends GetxController {
  var teacher = Teacher();
  
  void convertToUpperCase() {
     teacher.name.value = teacher.name.value.toUpperCase();
  }
}

第三步:實(shí)例化控制器并使用


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) {

    // 即使不使用控制器實(shí)例也會(huì)被創(chuàng)建
    // tag將用于查找具有標(biāo)簽名稱的實(shí)例
    // 控制器在不使用時(shí)被處理,但如果永久為真,則實(shí)例將在整個(gè)應(yīng)用程序中保持活動(dòng)狀態(tài)
    MyController myController = Get.put(MyController(), permanent: true);
    // MyController myController = Get.put(MyController(), tag: "instancel", permanent: true);

    // 實(shí)例將在使用時(shí)創(chuàng)建
    // 它類似于'permanent',區(qū)別在于實(shí)例在不被使用時(shí)被丟棄
    // 但是當(dāng)它再次需要使用時(shí),get 將重新創(chuàng)建實(shí)例
    // Get.lazyPut(()=> MyController());
    // Get.lazyPut(()=> MyController(), tag: "instancel");

    // Get.put 異步版本
    // Get.putAsync<MyController>(() async  => await MyController());

    // 每次都將返回一個(gè)新的實(shí)例
    // Get.create<MyController>(() => MyController());

    return Scaffold(
      appBar: AppBar(
        title: Text("GetXController"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () {
                // 實(shí)例使用的tag創(chuàng)建
                // Get.find<MyController>(tag: 'instancel');

                Get.find<MyController>();
              },
              child: Text("別點(diǎn)我"))
          ],
        ),
      ),
    );
  }
}

Get Service

這個(gè)類就像一個(gè) GetxController,它共享相同的生命周期onInit()、onReady()onClose()。 但里面沒(méi)有 "邏輯"。它只是通知GetX的依賴注入系統(tǒng),這個(gè)子類不能從內(nèi)存中刪除。所以如果你需要在你的應(yīng)用程序的生命周期內(nèi)對(duì)一個(gè)類實(shí)例進(jìn)行絕對(duì)的持久化,那么就可以使用GetxService。

第一步:創(chuàng)建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 的值為: $count");
    await prefs.setInt("counter", count);
  }
}

第二步:初始化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';

/// 初始化服務(wù)
Future<void> main() async {
  await initServices();
  runApp(MyApp());
}

Future<void> initServices() async {
  print("初始化服務(wù)");
  await Get.putAsync(() async => await Service());
  print("所有服務(wù)啟動(dòng)");
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: "GetX",
      home: GetXServiceExample(),
    );
  }
}

第三步:調(diào)用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("點(diǎn)我加1"))
          ],
        ),
      ),
    );
  }
}

GetX Binding

在我們使用GetX狀態(tài)管理器的時(shí)候,往往每次都是用需要手動(dòng)實(shí)例化一個(gè)控制器,這樣的話基本頁(yè)面都需要實(shí)例化一次,這樣就太麻煩了,而Binding 能解決上述問(wèn)題,可以在項(xiàng)目初始化時(shí)把所有需要進(jìn)行狀態(tài)管理的控制器進(jìn)行統(tǒng)一初始化,接下來(lái)看代碼演示:

第一步:聲明需要進(jìn)行的綁定控制器類


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 dependencies
    Get.lazyPut<BindingMyController>(() => BindingMyController());
    Get.lazyPut<BindingHomeController>(() => BindingHomeController());
  }
}



import 'package:get/get.dart';

class BindingHomeController extends GetxController {
  var count = 0.obs;
  void increment() {
    count++;
  }
}


import 'package:get/get.dart';

class BindingMyController extends GetxController {
  var count = 0.obs;
  void increment() {
    count++;
  }
}

第二步:在項(xiàng)目啟動(dòng)時(shí)進(jìn)行初始化綁定

綁定的方式有多種,在不同的情況下有不同的使用方式,這里介紹一種,如果需要更加詳細(xì)的介紹,觀看視頻將會(huì)是最佳的選擇。

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(),
    );
  }
}

第三步:在頁(yè)面中使用狀態(tài)管理器


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(
              "計(jì)數(shù)器的值為 ${Get.find<BindingMyController>().count}",
              style: TextStyle(color: Colors.red, fontSize: 30),
            )),
            SizedBox(height: 20,),
            ElevatedButton(
              onPressed: () {
                Get.find<BindingMyController>().increment();
              },
              child: Text("點(diǎn)擊加1")
            ),
            SizedBox(height: 20,),
            ElevatedButton(
              onPressed: () {
                Get.to(BHome());

                // Get.toNamed("/bHome");

                // Get.to(BHome(), binding: BHomeControllerBinding());
              },
              child: Text("跳轉(zhuǎn)去首頁(yè)")
            ),
          ],
        ),
      ),
    );
  }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容