Flutter – SVG Image as Button
Last Updated :
14 May, 2023
In this article, we will see how to make the SVG image a button in Flutter so that we can perform actions. A sample video is given below to get an idea about what we are going to do in this article.
How to Use?
You can use the Gesture Detector to add click functionality to any Widget in Flutter.
Dart
GestureDetector(
onTap: () {
},
child:
),
|
And the child svg Widget is as simple as using this lib (since Flutter still doesn’t have native SVG support): https://pub.dev/packages/flutter_svg
Dart
SvgPicture.asset(
'assets/images/s1.svg' ,
semanticsLabel: 'My SVG Image' ,
height: 100,
width: 70,
),
|
Step By Step Implementation
Step 1: Create a New Project in Android Studio
To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.
Step 2: Add the material package that gives us the important methods and then call the runApp method in the main function that will call our application.
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
void main() {
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(primarySwatch: Colors.green),
home: RunMyApp()));
}
Step 3: Now we have to make a stateless widget RunMyApp Because our application does not go to change its state. This class returns the scaffold widget, and further wraps the SvgPicture widget with Gesture Detector to get the clickable feature.
class RunMyApp extends StatelessWidget {
const RunMyApp({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: GestureDetector(
onTap: () {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('Image Clicked!')));
},
child: SvgPicture.asset(
'assets/images/s1.svg',
semanticsLabel: 'My SVG Image',
height: 100,
width: 70,
),
),
),
);
}
}
Code Example
Dart
import 'package:flutter/material.dart' ;
import 'package:flutter_svg/flutter_svg.dart' ;
void main() {
runApp(MaterialApp(
debugShowCheckedModeBanner: false ,
theme: ThemeData(primarySwatch: Colors.green),
home: RunMyApp()));
}
class RunMyApp extends StatelessWidget {
const RunMyApp({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: GestureDetector(
onTap: () {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text( 'Image Clicked!' )));
},
child: SvgPicture.asset(
'assets/images/s1.svg' ,
semanticsLabel: 'My SVG Image' ,
height: 100,
width: 70,
),
),
),
);
}
}
|
Output
Share your thoughts in the comments
Please Login to comment...