Flutter学习笔记 —— 关于Getx框架中如何手动注销控制器

前言

最近在开发Flutter项目时,一个登出功能我认为几分钟就能弄完了,直到发现单凭 Getx 的路由跳转并不能自动注销相关的控制器,查阅百度一直无果。

经过花费一定时间查阅Getx 源码后发现

一个拓展吸引了我的注意

extension Inst on GetInterface {
...


  /// Deletes the `Instance<S>`, cleaning the memory and closes any open
  /// controllers (`DisposableInterface`).
  ///
  /// - [tag] Optional "tag" used to register the Instance
  /// - [force] Will delete an Instance even if marked as `permanent`.
  Future<bool> delete<S>({String? tag, bool force = false}) async =>
      GetInstance().delete<S>(tag: tag, force: force);

  /// Deletes all Instances, cleaning the memory and closes any open
  /// controllers (`DisposableInterface`).
  ///
  /// - [force] Will delete the Instances even if marked as `permanent`.
  Future<void> deleteAll({bool force = false}) async =>
      GetInstance().deleteAll(force: force);
...
 
}

Get是继承于 GetInteface 接口,那么自然拥有这个拓展

可以看到里面有两个关键方法,delete() 、deleteAll()

通过翻译可得知,可以通过remove方法移除指定泛型的某个对象

那么知道该怎么删除了,之后上一个我的状态管理代码

实例

/**
 * @author Marinda
 * @date 2022/11/24 17:55
 * @desc Get页面管理器
 */
class PageManager{

  /*
   * 销毁所有页面数据重新加载!
   * 等找到可以模拟安卓返回键,让Get自动注销相关控制器就删除
   */
  void destoryAllPage(){
    Get.delete<IndexLogic>();
    Get.delete<MyLogic>();
    Get.delete<ContactsLogic>();
    Get.delete<MessageLogic>();
    Get.delete<UpdDetailsLogic>();
    Get.delete<UpdUserLogic>();
    Get.delete<TaskLogic>();
    Get.delete<SearchLogic>();
    Get.delete<ReportLogic>();
    Get.delete<DetailsLogic>();
  }
}

我这里并没有使用removeAll(),因为会移除全部的Get状态。

调用以下相关方法即可实现

[GETX] "IndexLogic" onDelete() called
[GETX] "IndexLogic" deleted from memory
[GETX] "MyLogic" onDelete() called
[GETX] "MyLogic" deleted from memory
[GETX] Instance "ContactsLogic" already removed.
[GETX] "MessageLogic" deleted from memory
[GETX] Instance "UpdDetailsLogic" already removed.
[GETX] "UpdUserLogic" deleted from memory
[GETX] "TaskLogic" onDelete() called
[GETX] "TaskLogic" deleted from memory
[GETX] "SearchLogic" deleted from memory
[GETX] "ReportLogic" onDelete() called
[GETX] "ReportLogic" deleted from memory
[GETX] Instance "DetailsLogic" already removed.
[GETX] GOING TO ROUTE /login

感谢你的观看!

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇