1

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;
  }
Nashaf
  • 23
  • 7

2 Answers2

1

you need to change the state not items :

   toggleFavorite(index) {
     state[index].isFavotie = !state[index].isFavotie;
     state = [...state];
  }
Hosam Hasan
  • 564
  • 4
  • 11
  • Thank you! I already tried this but still same `void toggleFavorite(index) { state[index].isFavotie = !state[index].isFavotie; state = [...state]; }` – Nashaf Jan 10 '22 at 12:03
  • this is how i use provider in icon button is this okay ?? `ref.read(productsProvider.notifier).toggleFavorite(index);` – Nashaf Jan 10 '22 at 12:07
  • this is the provider `final productsProvider = StateNotifierProvider((ref) => ProductsNotyfier());` – Nashaf Jan 10 '22 at 12:34
  • Please share the code of the list that watches the state provider – Hosam Hasan Jan 10 '22 at 15:52
  • `ref.read(productsProvider.notifier).toggleFavorite(index);` – Nashaf Jan 11 '22 at 05:54
0

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.

Oprimus
  • 1,652
  • 3
  • 11
  • 20