GetX学习04 GetView

2,041 阅读2分钟

这是我参与8月更文挑战的第4天,活动详情查看:8月更文挑战

今天我们学习下GetView、GetWidget、GetxService

1.GetView

它是一个对已注册的Controller有一个名为controller的getter的const Stateless的Widget,仅此而已。

 class AwesomeController extends GetxController {
   final String title = 'My Awesome View';
 }

  // 一定要记住传递你用来注册控制器的`Type`!
 class AwesomeView extends GetView<AwesomeController> {
   @override
   Widget build(BuildContext context) {
     return Container(
       padding: EdgeInsets.all(20),
       child: Text( controller.title ), // 只需调用 "controller.something"。
     );
   }
 }

2.GetWidget

大多数人都不知道这个Widget,或者完全搞不清它的用法。 这个用例非常少见且特殊:它 "缓存 "了一个Controller,由于_cache_,不能成为一个 "const Stateless"(因为_cache_,所以不能成为一个const Stateless)。

那么,什么时候你需要 "缓存 "一个Controller?

如果你使用了GetX的另一个 "不常见 "的特性 Get.create()

Get.create(()=>Controller()) 会在每次调用时生成一个新的Controller Get.find<Controller>()

你可以用它来保存Todo项目的列表,如果小组件被 "重建",它将保持相同的控制器实例。

3.GetxService

这个类就像一个 "GetxController",它共享相同的生命周期("onInit()"、"onReady()"、"onClose()")。 但里面没有 "逻辑"。它只是通知GetX的依赖注入系统,这个子类不能从内存中删除。

所以这对保持你的 "服务 "总是可以被Get.find()获取到并保持运行是超级有用的。比如 ApiServiceStorageServiceCacheService

Future<void> main() async {
  await initServices(); /// 等待服务初始化.
  runApp(SomeApp());
}

/// 在你运行Flutter应用之前,让你的服务初始化是一个明智之举。
////因为你可以控制执行流程(也许你需要加载一些主题配置,apiKey,由用户自定义的语言等,所以在运行ApiService之前加载SettingService。
///所以GetMaterialApp()不需要重建,可以直接取值。
void initServices() async {
  print('starting services ...');
  ///这里是你放get_storage、hive、shared_pref初始化的地方。
  ///或者moor连接,或者其他什么异步的东西。
  await Get.putAsync(() => DbService().init());
  await Get.putAsync(SettingsService()).init();
  print('All services started...');
}

class DbService extends GetxService {
  Future<DbService> init() async {
    print('$runtimeType delays 2 sec');
    await 2.delay();
    print('$runtimeType ready!');
    return this;
  }
}

class SettingsService extends GetxService {
  void init() async {
    print('$runtimeType delays 1 sec');
    await 1.delay();
    print('$runtimeType ready!');
  }
}

实际删除一个GetxService的唯一方法是使用Get.reset(),它就像"热重启 "你的应用程序。

所以如果你需要在你的应用程序的生命周期内对一个类实例进行绝对的持久化,请使用GetxService