Search code examples
flutterflutter-provider

Why can't I instantiate values ​from my provider?


You will see what I want is to call the variable of my provider, which in this case is:

Icon _hearticon = const Icon(
    Icons.favorite_border,
  );

and also the method that changes the shape of the icon when pressed.

void changeHeart() {
    if (_hearticon.icon == Icons.favorite_border) {
      _hearticon = const Icon(
        Icons.favorite,
      );
    } else {
      _hearticon = const Icon(
        Icons.favorite_border,
      );
    }
    notifyListeners();
  }

here the complete provider

import 'package:flutter/material.dart';

class HeartIconState with ChangeNotifier {
  Icon _hearticon = const Icon(
    Icons.favorite_border,
  );
  void changeHeart() {
    if (_hearticon.icon == Icons.favorite_border) {
      _hearticon = const Icon(
        Icons.favorite,
      );
    } else {
      _hearticon = const Icon(
        Icons.favorite_border,
      );
    }
    notifyListeners();
  }

  Icon get hearticon => _hearticon;

  set hearticon(Icon value) {
    _hearticon = value;
    notifyListeners();
  }
}

and the way i'm calling them:

    IconButton(
   icon: Heart.hearticon,
   color: Colors.red,
   iconSize: 25.0,
  onPressed: Heart.changeHeart,
           ),

I had already done it this way when I was handling the state of a color to change from black to white and vice versa.


Solution

  • changenotifier is different with usual class. it contain state.

    i think you wrong when calling the state. here one of the workaround by wraping the widget with Consumer builder to get the state value.

    Consumer<AppState>(builder: (context, state, child ) {
           return IconButton(icon: state.hearticon,
               color: Colors.red,
               iconSize: 25.0,
               onPressed: state.changeHeart,
               ),
            }
         ) 
    

    it should be work.