Nashaf
Nashaf

Reputation: 43

Flutter Riverpod UI change only when i hot-reload

When i call toggleFavorite function using a icon button the state is changing but ui not update but when i hot reload it's update. i checked some similar question on stackoverflow but i couldn't figure it out.

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;
  }

Upvotes: 1

Views: 1093

Answers (3)

Doan Thai
Doan Thai

Reputation: 685

The state should be immutable. Use @immutable or lib @freezed for Product. See here.

toggleFavorite(index) {
  state = [
    for (final (i, product) in state.indexed)
      if (i == index)
        product.copyWith(isFavotie : !product.isFavotie )
      else
        product,
  ];
}

Upvotes: 0

Oprimus
Oprimus

Reputation: 1898

Hot reload preserves the app state. It's faster as it does not rerun main() or ````initState()```. If you want to hot restart the app state, then use hot restart "R" (capital R) in the terminal in debug mode in VSCode or (⇧⌘\ in Android Studio, ⇧⌘F5 in VSCode). See docs here.

Upvotes: 0

Hosam Hasan
Hosam Hasan

Reputation: 692

you need to change the state not items :

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

Upvotes: 1

Related Questions