简体   繁体   English

Flutter no state 在 GestureDetector 中使用 Navigator.of(context).push(..) 时发生变化

[英]Flutter no state changes when using Navigator.of(context).push(..) in a GestureDetector

I'm building a product store right now.我现在正在建立一个产品商店。 I have a product Card which is using a GestureDetector to navigate to the SingleProductPage.我有一张使用 GestureDetector 导航到 SingleProductPage 的产品卡。 In my SingleProductPage I am using a callback function to add/remove this product as a favorite.在我的 SingleProductPage 中,我使用回调 function 将此产品添加/删除为收藏。 When using one of these Callback function, my Stateful Widget will change the state to the new favorite product list.当使用其中一个回调 function 时,我的 Stateful Widget 会将 state 更改为新收藏的产品列表。 But for some reason, my SingleProductPage doesn't get the new state and the page wont rebuild.但由于某种原因,我的 SingleProductPage 没有得到新的 state 并且页面不会重建。 All other widgets are getting rebuilded when changing the state.更改 state 时,所有其他小部件都将重新构建。

This is my GestureDestectore in the product card:这是我在产品卡中的 GestureDesectore:

GestureDetector(
        onTap: () {
          Navigator.of(context).push(MaterialPageRoute(
              builder: (_) => SingleProductPage(product, account, favorites,
                  addFavoriteCallback, removeFavoriteCallback)));
        },

This is what my favorite button does on remove favorite:这是我最喜欢的按钮在删除收藏夹时所做的:

    if(favoriteId != null) {
       removeFavoriteCallback(favoriteId);
    }

And this is what happens when the removeFavoriteCallback gets executed:这就是执行 removeFavoriteCallback 时发生的情况:

void onRemoveFavorite(int favoriteId) {
    if (_userAccount != null) {
      favoriteService
          .deleteFavorite(
              FavoriteDeleteRequest(_userAccount!.userId, favoriteId))
          .then((value) => getFavoritesByUser());
    }
  }

  void getFavoritesByUser() {
    if (_userAccount != null) {
      favoriteService.getFavoritesByUser(_userAccount!.userId).then((value) => {
            if (value != null)
              {
                setState(() {
                  _favorites = Favorites(value.products);
                })
              }
          });
    }
  }

As I understand you call a function that has setState() in it, which updates the widget function is called from(which is product card in your example), simple solution would be to wrap in setState() as well据我了解,您调用其中包含setState()的 function 会更新小部件 function 的调用来源(在您的示例中是产品卡),简单的解决方案是也包含在setState()

if(favoriteId != null) {
    setState(() =>removeFavoriteCallback(favoriteId));
}

so you update your single card widget所以你更新你的单卡小部件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM