Icon change provider index

Viewed 26

Hi I want to change the icon when pressed button.
So I used provider method.


Icon Widget

class LockeryIcon extends StatelessWidget {
  final String text;
  LockeryIcon({required this.text});

  @override
  Widget build(BuildContext context) {
   return IconButton(
  onPressed: () {
    Navigator.of(context).pushNamed(SecondView);
    print(text);
  },
  icon: Icon(context.watch<ProviderA>().isIcon),
);
  }
}


Listview builder

class Abc extends StatelessWidget {
  final List _lock1 = [
    'abc 1',
    'abc 2',
    'abc 3',
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
        shrinkWrap: true,
        itemCount: _lock1.length,
        itemBuilder: (context, index) {
          return Padding(
            padding: const EdgeInsets.all(30.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                LockeryIcon(text: _lock1[index]),                   
              ],
            ),
          );
        },
      ),
    );
  }
}


Main Screen

class MainView extends StatelessWidget {
  const MainView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Abc(),
    );
  }


Second View

class SecondView extends StatelessWidget {
  const SecondView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: TextButton(
        onPressed: () {
          context.read<LockeryProvider>().change();
          Navigator.of(context).pop();
        },
        child: Text('Done'),
      ),
    );
  }
}


Provider

class ProviderA with ChangeNotifier {
  IconData _isIcon = Icons.access_time_filled_sharp;

  IconData get isIcon => _isIcon;

  void change() {
    _isIcon = Icons.add_location;
    notifyListeners();
  }
}


My problem is when I clicked this all the icons are being changed.
Is there a way to pass index to only change the relevant button???
Or my method is not correct?
Please help me on this
Thank you

1 Answers

You have to store an integer in your provider:

class ProviderA with ChangeNotifier {
  int _index = -1;

  int get isIndex => _index;

  void change(int index) {
    _index = index;
    notifyListeners();
  }
}

and check the index in your Icon class like this:

class LockeryIcon extends StatelessWidget {
  final String text;
  final int listViewIndex;
  LockeryIcon({required this.text,required this.listViewIndex});

  @override
  Widget build(BuildContext context) {
    return IconButton(
      onPressed: () {
        Navigator.of(context).pushNamed(SecondView);
        print(text);
      },
      icon: Icon(context.watch<ProviderA>().isIndex == listViewIndex ? firstIcon:secondIcon),
    );
  }
}

finally, use the change function in which you press your button.

Related