Creating Beautiful UI with flutter svg Package: SVG Integration and Animation 2024

flutter svg

Written and reviewed by: 

SHARE

Hello, Flutter Developers! As a Flutter developer, you have probably heard about SVG (scalable vector graphics).If you want to create a stunning and beautiful UI in your Flutter app, SVGs are the secret weapon many developers swear by. By using SVG, you can elevate your app’s visuals.

In this blog, we are going to explore how to use the flutter svg package to integrate SVGs into your Flutter projects with some real-life examples.

Table of Contents

Why use SVGs?

 

SVG stands for Scalable Vector Graphics. It’s like the James Bond of images—scalable, suave, and endlessly cool. 

SVGs (Scalable Vector Graphics) are the superheroes of the image world. Unlike raster images (JPG, PNG), SVGs are vector-based, meaning they scale beautifully without losing quality. Whether your user is on a tiny phone or a gigantic monitor, your graphics will look crisp and perfect.

5 Benefits of SVG

 
Let’s summarize the five benefits of SVG.
 
  • Scalability without loss of quality.
  • Smaller file sizes compared to raster images.
  • It is easy to manipulate with CSS and JavaScript.
  • Better performance and faster load times.
  • High resolution on any screen size.

Why use the flutter svg package?

 
If SVG is James Bond, then flutter svg is Q. It provides all the fancy gadgets to make your UI beautiful and stunning.
 
Flutter’s flutter svg package allows you to draw SVG files effortlessly. It makes your app look professional. It’s like having your cake and eating it too—only this cake doesn’t get pixelated.
 

Getting Started with flutter svg 

 

First things first, let’s get flutter svg into our Flutter project. You don’t need to send smoke signals or learn morse code. Just follow these simple steps:

1. Open your pubspec.yaml file.

2. Add flutter svg under dependencies:

				
					dependencies:
  flutter_svg: ^2.0.10+1

				
			

3. Run flutter pub get in your terminal, and voilà! You’re ready to roll.

Loading SVG using flutter svg:

 
Loading SVG is easy peasy. Here is a basic example:
				
					import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Flutter SVG')),
        body: Center(
          child: SvgPicture.asset(
         'assets/tic-tac-toe-2.png',
          width: 100,
          height:100),
        ),
      ),
    );
  }
}

				
			

In this snippet, replace “assets/tic-tac-toe-2.png” with the path to your SVG file. Simple, right? It’s almost like magic, but without the wand and the hat.

Output:

flutter svg

Network SVGs using flutter svg

 
You can also load SVGs from a network. This is perfect for those times when you need to pull in images dynamically. Here’s how:
				
					body: Center(
  child: SvgPicture.network(
    'https://example.com/my_image.svg',
    placeholderBuilder: (BuildContext context) => CircularProgressIndicator(),
  ),
),

				
			

Now your app can fetch SVGs from the internet. Just make sure your users have a decent internet connection. (Or else you’ll be showing more progress indicators than actual images.)

Colorizing SVGs using flutter svg

 

Sometimes, you might want to change the color of an SVG on the fly. With flutter svg, it’s a breeze. Here’s an example:

				
					SvgPicture.asset(
  'assets/my_image.svg',
  color: Colors.red,
),

				
			

That’s right! You can now colorize your SVGs like a pro. It’s like having a coloring book, but without the risk of coloring outside the lines.

Using SVGs for Icons

 
One of the coolest things about SVGs is their versatility. Need an icon? SVGs got you covered. Here’s how you can use an SVG as an icon:
				
					IconButton(
  icon: SvgPicture.asset('assets/icons/my_icon.svg'),
  onPressed: () {
    // Do something
  },
);

				
			

Using SVGs for icons can help maintain a consistent look and feel across different screen sizes and resolutions. Plus, it saves you from the dreaded “fuzzy icon syndrome” that PNGs sometimes suffer from.

Bonus: Animating SVGs

 
Want to add some pizzazz to your app? Animate those SVGs! While flutter svg doesn’t support animation directly, you can use it in combination with other Flutter animation tools. Here’s a simple example using a Transform widget:
				
					class AnimatedSvg extends StatefulWidget {
  @override
  _AnimatedSvgState createState() => _AnimatedSvgState();
}

class _AnimatedSvgState extends State<AnimatedSvg>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    )..repeat(reverse: true);
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      builder: (context, child) {
        return Transform.scale(
          scale: 1.0 + _controller.value,
          child: SvgPicture.asset('assets/my_image.svg'),
        );
      },
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}

				
			

Here, we’re scaling the SVG back and forth. It’s a bit like watching a balloon inflate and deflate, only more mesmerizing.

>>Check out our animation related articles : Creating Custom Animations with flutter_animate: A Guide for Flutter Enthusiasts 2024

Output:

Common Pitfals

 

1. Large SVG Files

 

If your SVG files are larger than your cat on Thanksgiving, they might slow down your app. Always optimize SVGs before using them in your app. Tools like SVGO can help reduce file size without losing quality. Remember, nobody likes a bloated app. (Except maybe your cat.)

2. Unsupported Features

 

Not all SVG features are supported by flutter svg. Filters, for example, are not supported. If you need advanced features, consider pre-processing your SVGs or using alternative methods. It’s like finding out your favorite pizza place doesn’t have pineapple—disappointing, but manageable.

3. Error Handling

 

Always handle errors gracefully. Network SVGs might fail to load due to connectivity issues. Make sure to provide fallback mechanisms, like showing a placeholder image. It’s like having an umbrella when you forget to check the weather—better safe than sorry.

				
					SvgPicture.network(
  'https://example.com/my_image.svg',
  placeholderBuilder: (BuildContext context) => CircularProgressIndicator(),
  errorBuilder: (context, error, stackTrace) => Icon(Icons.error),
),

				
			

Conclusion

 

Using flutter svg is like adding a touch of elegance to your Flutter app without breaking a sweat. It’s powerful, flexible, and easy to use. Whether you’re a novice developer or a seasoned pro, flutter svg can help you create stunning UIs that look great on any screen size.

So go ahead, embrace the power of SVGs, and make your Flutter app shine. Just remember, with great power comes great responsibility—don’t let those SVGs pixelate! Now, get out there and start fluttering with flutter svg. And may your UI be as beautiful as a perfectly brewed cup of coffee. Cheers! ☕

FAQ

Using SVGs ensures your images are scalable, have smaller file sizes, are easy to manipulate, provide better performance, and look high-resolution on any screen size.

Yes, while flutter_svg doesn’t support direct animation, you can animate SVGs using Flutter’s animation tools like Transform and Animated Builder.

Use the errorbuilder property in SvgPicture.network to handle errors gracefully and show a placeholder or error icon.

flutter_svg supports most SVG features, but some advanced features like filters are not supported. Pre-process your SVGs if necessary.

Use tools like SVGO to optimize SVG files by reducing file size without losing quality.

Written and reviewed by

Picture of Muhammad Naeem
Muhammad Naeem
Professional Flutter Developer
Scroll to Top