Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an Onclick event to an image which is inside CircleAvatar Widget in flutter?

Tags:

flutter

dart

I have a circular image inside circleAvatar on clicking which I want to open an alert dialog box. My question is how to add clicking event inside CircleAvatar?

This is my code :

        Column(children: <Widget>[
        SizedBox(height: 32.0),
        CircleAvatar(
          radius: 55.0,
          backgroundImage: ExactAssetImage('assets/cat.jpg'),
        ),
        Container(
          height: 20.0,
        ),
        Text('01:29:30'),
        Text(
          'Avik Kumar Mandal',
          style: TextStyle(fontSize: 20),
        ),

Expected: onclick event on the image which is inside Circular avatar P.s it is a profile picture on clicking which a dialog box should appear.

like image 790
Prianca Avatar asked Jun 26 '19 13:06

Prianca


People also ask

How do you use CircleAvatar in flutter?

This property applies a background image to the CircleAvatar widget. child: The child property takes the widget to be placed below the CircleAvatar widget inside the widget tree or the widget to be displayed inside the circle. foregroundColor: This property holds the Color class (final) as the parameter value.


3 Answers

You can wrap your circular avatar with a gesture detector

Column(children: <Widget>[
        SizedBox(height: 32.0),
        GestureDetector(
                onTap: () {
                 //do what you want here
                },
                child:  CircleAvatar(
                       radius: 55.0,
                        backgroundImage: ExactAssetImage('assets/cat.jpg'),
                ), 
           ),

        Container(
          height: 20.0,
        ),
        Text('01:29:30'),
        Text(
          'Avik Kumar Mandal',
          style: TextStyle(fontSize: 20),
        ),

Or

InkWell(
  onTap: () => print("image clicked"),
  child: AnyWidget()
),

Now generalize my answer.

If you want to set OnClickListener to some widget that onTap is not implemented by default, then you should wrap the widget with GestureDetector or InkWeel

like image 192
Jasurbek Avatar answered Sep 28 '22 19:09

Jasurbek


You can use GestureDetector but you will lose ripple effect on image click, so a better solution would be to use InkWell. Wrap your CircleAvatar in InkWell

InkWell(
  onTap: () => print("image clicked"),
  child: CircleAvatar(
    backgroundImage: ExactAssetImage('assets/cat.jpg'),
    radius: 55,
  ),
),
like image 34
CopsOnRoad Avatar answered Sep 28 '22 19:09

CopsOnRoad


Another way is to wrap it in an IconButton, which has the benefit of a circular ripple effect.

IconButton(
  icon: CircleAvatar(),
  onPressed: () {},
)
like image 37
Elfor Avatar answered Sep 28 '22 21:09

Elfor