Search code examples
flutterdarticonsiconbutton

How change the Icon of an IconButton when it is pressed


I want to know how I can change the Icon of an IconButton when it is pressed. (Favorite_border to Favorite). I tried somethings but it doesn't works. Maybe it is easy but I am a beginner and I don't understand very well how it is works.

Update

import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../recyclerview/data.dart';
import 'package:watch/constants.dart';

int itemCount = item.length;
List<bool> selected = new List<bool>();

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  initState() {
    for (var i = 0; i < itemCount; i++) {
    selected.add(false);
    }
    super.initState();
  }
 
  Icon notFavorite = Icon(Icons.favorite_border, size: 25,);
  Icon inFavorite = Icon(Icons.favorite, size: 25,);

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
         title: Text('Accueil', style: kAppBarStyle,),
          //backgroundColor: Colors.white,  
          elevation: 0,
      ),
      body:  ListView.builder(
        itemCount: itemCount,
        itemBuilder: (BuildContext context, int index) {
      return Container(
        child: new Row(
          children: <Widget>[
            //Image
            new Container(
              margin: new EdgeInsets.all(5.0),
              child: new CachedNetworkImage(
                imageUrl: item[index].imageURL,
                height: MediaQuery.of(context).size.width / 4,
                width: MediaQuery.of(context).size.width / 2,
                fit: BoxFit.cover,
              ),
            ),
            //Text
            Expanded(
              child: new Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Spacer(),               
                //Titre
                Container(
                  padding: const EdgeInsets.only(bottom: 75.0, top: 10.0 ),
                  child: Text(
                    item[index].title,
                    style: kItemTitle,
                  ),
                ),
                //Decription
                Container(
                  padding: const EdgeInsets.only(left: 10.0, top: 10.0),
                  child:Text(
                    item[index].description,
                    style: kItemDescription,
                  ),
                ),
                //Favoris
                Spacer(),
                GestureDetector(
                  child: Container(
                    padding: const EdgeInsets.only(right: 10.0, top: 3.0),
                    child: selected.elementAt(index) ? inFavorite : notFavorite,
                  ),
                  onTap: () {
                    setState(() {
                      selected[index] = !selected.elementAt(index);
                    });
                    },
                ),
              ],
            ),
          ),
        ],
      ),
    );
    }
    )
  );
}
}

It is a ListView with Images, Texts and the Favorite Button and it works fine.


Solution

  • custom radio button (some IconButton in ListView that change their icons):

    main.dart file :

    import 'package:flutter/material.dart';
    import 'my_home_page.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
            visualDensity: VisualDensity.adaptivePlatformDensity,
          ),
          home: MyHomePage(title: 'Flutter Demo Home Page'),
        );
      }
    }
    

    my_home_page.dart file:

    import 'package:flutter/material.dart';
    
    int itemCount = 5;
    List<bool> selected = new List<bool>();
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
    
       @override
       initState() {
         for (var i = 0; i < itemCount; i++) {
            selected.add(false);
         }
         super.initState();
       }
    
      Icon firstIcon = Icon(
        Icons.radio_button_on, // Icons.favorite
        color: Colors.blueAccent, // Colors.red
        size: 35,
      );
      Icon secondIcon = Icon(
        Icons.radio_button_unchecked, // Icons.favorite_border
        color: Colors.grey,
        size: 35,
      );
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: Center(
            child: ListView.builder(
                itemCount: itemCount,
                itemBuilder: (BuildContext context, int index) {
                  return IconButton(
                    icon: selected.elementAt(index) ? firstIcon : secondIcon,
                    onPressed: () {
                      try {
                        // your code that you want this IconButton do
                        setState(() {
                          selected[index] = !selected.elementAt(index);
                        });
                        print('tap on ${index + 1}th IconButton ( change to : ');
                        print(selected[index] ? 'active' : 'deactive' + ' )');
                      } catch (e) {
                        print(e);
                      }
                    },
                  );
                }),
          ),
        );
      }
    }