【问题标题】:Flutter Riverpod UI change only when i hot-reloadFlutter Riverpod UI 仅在我热重载时更改
【发布时间】:2022-01-10 09:52:26
【问题描述】:

当我使用图标按钮调用 toggleFavorite 函数时,状态正在改变,但 ui 不会更新,但当我 热重载 时它会更新。我在stackoverflow上检查了一些类似的问题,但我无法弄清楚。

class ProductsNotyfier extends StateNotifier<List<Product>> {
  ProductsNotyfier()
      : super([
          Product(
            id: 'p1',
            title: 'Red Shirt',
            description: 'A red shirt - it is pretty red!',
            price: 29.99,
            imageUrl:
                'https://images.unsplash.com/photo-1602810320073-1230c46d89d4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=687&q=80',
          ),
          Product(
            id: 'p2',
            title: 'Trousers',
            description: 'A nice pair of trousers.',
            price: 59.99,
            imageUrl:
                'https://images.unsplash.com/photo-1603252110971-b8a57087be18?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80',
          ),
          
        ]);

  List<Product> get items {
    return [...state];
  }

  toggleFavorite(index) {
    items[index].isFavotie = !items[index].isFavotie;
  }

【问题讨论】:

    标签: flutter dart flutter-dependencies riverpod flutter-state


    【解决方案1】:

    您需要更改 state 而不是 items

       toggleFavorite(index) {
         state[index].isFavotie = !state[index].isFavotie;
         state = [...state];
      }
    

    【讨论】:

    • 谢谢!我已经试过了,但还是一样void toggleFavorite(index) { state[index].isFavotie = !state[index].isFavotie; state = [...state]; }
    • 这就是我在图标按钮中使用提供程序的方式可以吗? ref.read(productsProvider.notifier).toggleFavorite(index);
    • 这是提供者final productsProvider = StateNotifierProvider((ref) =&gt; ProductsNotyfier());
    • 请分享观看状态提供者列表的代码
    • ref.read(productsProvider.notifier).toggleFavorite(index);
    【解决方案2】:

    热重载会保留应用状态。它更快,因为它不会重新运行 main() 或 ````initState()```。如果要热重启应用程序状态,则在 VSCode 的调试模式下在终端中使用热重启“R”(大写的 R)或(Android Studio 中的⇧⌘\,VSCode 中的⇧⌘F5)。请参阅文档here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      • 2021-08-20
      • 2021-02-06
      • 2021-07-30
      • 2021-11-29
      相关资源
      最近更新 更多