首页 > 解决方案 > 在 Futter (GET X) 中使用不同的参数弹出并推回相同的路由

问题描述

我有2个屏幕,

我在这里要做的是,当用户进入详细信息屏幕并单击抽屉中的项目时,详细信息屏幕应该弹出并使用新参数推回。

到目前为止的代码,

路线

GetPage(
  name: '/market-detail',
  page: () => MarketDetail(),
  binding: MarketDetailBinding(),
),

捆绑

class MarketDetailBinding extends Bindings {
  @override
  void dependencies() {
   Get.lazyPut(() => MarketDetailController());
  }
}

单击屏幕一中的操作

onTap: () {
      Get.toNamed('market-detail',
          arguments: {'market': market});
    },

详细画面类

class MarketDetail extends GetView<MarketDetailController> {
  final Market market = Get.arguments['market'];
}

单击详细屏幕侧边栏的操作

onTap: () {
        Get.back();
        Get.back();
        Get.toNamed('market-detail',
            arguments: {'market': market});
      },

首先 Get.back() 是关闭抽屉,然后移除路由并再次推回相同的路由,

预期行为

MarketDetailController 应该从内存中删除并重新放置,

实际发生的事情

在我热启动应用程序(通过单击保存)之前,控制器仅被删除并且不会在抽屉单击操作中恢复记忆。

如果有人理解它,请帮助我被困在这里。

标签: flutterflutter-getx

解决方案


正如我所看到的,您正在尝试使用不同的参数弹出并推送相同的路由,以便更新该路由上的某个元素。好吧,如果是这样的话,那么让我告诉你一个更好的方法。

在您的 MarketDetailController 类中,您应该添加这些:

class MarketDetailsController extends GetxController {
  // A reactive variable that stores the
  // instance of the market you're currently
  // showing the details of.....
  Rx<Market> currentMarket;

  // this method will be called once a new instance
  // of this controller gets created
  // we will use it to initialize the controller
  // with the required values
  @override
  void onInit() {
    // some code here....
    // .......

    // intializing the variable with the default value
    currentMarket = Market().obs;
    super.onInit();
  }

  void updateCurrentMarket(Market market) {
    // some code here if you need....

    // updating the reative variable value
    // this will get detected then by the Obx widgets
    // and they will rebuild whatever depends on this variable
    currentMarket.value = market;
  }
}

现在在您的页面 UI 中,您可以使用 Obx 小部件包装将显示市场详细信息的小部件,如下所示:

Obx(
  () {
    final Market currentMarket = controller.currentMarket.value;

    // now you have the market details you need
    // use it and return your widget

    return MyAwesomeMarketDetailsWidget();
  },
)

现在对于您的点击操作,它可以是这样的:

onTap: () => controller.updateCurrentMarket(myNewMarketValue)

这应该是它。另外,我建议您将 GetView 更改为 GetWidget 并将 Get.lazyPut() 更改为 Get.put()


推荐阅读