Skip to main content

Flutter Set Press Event on Image

To set onPress event on image widget we have to wrap the image inside InkWell widget. The InkWell support onClick function named as onTap(). This event fires on when user clicks the image or tap on the image button.

Flutter Set Press Event on Image:

1. Defining InkWell widget as parent and pass network image as Child. We are calling onTap() method which enables onPress event on Image.
      child: InkWell(
        onTap: sampleFunction,
        child: Ink.image(
          image: NetworkImage(buttonURL),
        ),
      ),
2. Creating a String variable in which we are passing image button URL.
final String buttonURL =
      'https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgj4lDPz-j9Wrt0IzK7-SBK_V3FPndBqvRMizn8q8diHeqWmIioAyefciLV6L_orJwoUE5mPGDq-vT_7SnzyqSpSyBR3_8XY2puHk5OOUeID-pDOKfbzR_78GXEkuZbvnpENxQu9A7BHhYIJGn0hD-agepCrJUus8O3BX-LaSB3kNaodV2u11XLyyq24qr_/s400/button.png';

3. Creating a sample function. We are calling this function on Image button on Tap event.
  void sampleFunction() {
    print('Image Clicked...');
  }
Source code for main.dart file:
import 'package:flutter/material.dart';

void main() => runApp(const App());

class App extends StatelessWidget {
  const App({super.key});

  final String buttonURL =
      'https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgj4lDPz-j9Wrt0IzK7-SBK_V3FPndBqvRMizn8q8diHeqWmIioAyefciLV6L_orJwoUE5mPGDq-vT_7SnzyqSpSyBR3_8XY2puHk5OOUeID-pDOKfbzR_78GXEkuZbvnpENxQu9A7BHhYIJGn0hD-agepCrJUus8O3BX-LaSB3kNaodV2u11XLyyq24qr_/s400/button.png';

  void sampleFunction() {
    print('Image Clicked...');
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            body: SafeArea(
                child: Center(
                    child: SizedBox(
      width: 238,
      child: InkWell(
        onTap: sampleFunction,
        child: Ink.image(
          image: NetworkImage(buttonURL),
        ),
      ),
    )))));
  }
}
Screenshots:
Flutter Set Press Event on Image

Comments