Search code examples
flutterflutter-provider

Why global theming not working if I wrap a widget with consumer provider?


Here I use secondary color as deepOrange in global theming using cololrscheme but when I wrap that widget with Consumer then it will not follow the global theming and apply some random color why that happens?

Below is my code with Consumer it didn't apply my color theming without consumer it will apply.

leading: Consumer<Product>(
        builder: (context, product, child) => IconButton(
          icon: Icon(
              product.isFavorite ? Icons.favorite : Icons.favorite_border),
          onPressed: () {
            product.toggleFavorite();
          },
          color: Theme.of(context).colorScheme.secondary,
        ),
      )

Solution

  • Here the problem caused by the name of BuildContext I use context for both consumer and also for the global theming context, so get rid of this problem I have to change the Consumer's BuildContext name to something else. like 'ctx' or whatever but global theming's BuildContext must be 'context' because we have to use context which is provided by widget in which you are.

    so here is the solution...

    leading: Consumer<Product>(
            builder: (ctx, product, child) => IconButton(
              icon: Icon(
                  product.isFavorite ? Icons.favorite : Icons.favorite_border),
              onPressed: () {
                product.toggleFavorite();
              },
              color: Theme.of(context).colorScheme.secondary,
            ),
          )