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

3 Answers 3

1

you need to change the state not items :

   toggleFavorite(index) {
     state[index].isFavotie = !state[index].isFavotie;
     state = [...state];
  }
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you! I already tried this but still same void toggleFavorite(index) { state[index].isFavotie = !state[index].isFavotie; state = [...state]; }
this is how i use provider in icon button is this okay ?? ref.read(productsProvider.notifier).toggleFavorite(index);
this is the provider final productsProvider = StateNotifierProvider((ref) => ProductsNotyfier());
Please share the code of the list that watches the state provider
ref.read(productsProvider.notifier).toggleFavorite(index);
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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.