Search code examples
fluttersvg

Is it possible to repeat an image (pattern) in SVG format in Flutter?


final kBackgroundImage = Image.asset(
  'assets/images/bg.png',
  repeat: ImageRepeat.repeat,
  height: double.infinity,
  width: double.infinity,
);

To do something like this with a SVG background image?


Solution

  • You can use flutter_svg_provider package to achieve the desired result. But keep in mind that the plugin is not actively maintained as of writing this answer.

    Sample code:

    import 'package:flutter/material.dart';
    import 'package:flutter_svg_provider/flutter_svg_provider.dart' as svg_provider;
    
    const svgPath = 'assets/sample_bg.svg';
    void main() {
      WidgetsFlutterBinding.ensureInitialized();
      runApp(const RepeatativeSvgBackgroundExample());
    }
    
    class RepeatativeSvgBackgroundExample extends StatelessWidget {
      const RepeatativeSvgBackgroundExample({super.key});
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          theme: ThemeData.light(
            useMaterial3: true,
          ),
          home: Scaffold(
            appBar: AppBar(title: const Text('Svg Repeatative Background')),
            body: _HomePage(),
          ),
        );
      }
    }
    
    class _HomePage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Container(
          height: double.infinity,
          width: double.infinity,
          decoration: const BoxDecoration(
            image: DecorationImage(
                image: svg_provider.Svg(svgPath, size: Size.square(40)),
                repeat: ImageRepeat.repeat,
                fit: BoxFit.none),
          ),
        );
      }
    }
    
    

    pubspec.yaml

    name: temp
    description: A new Flutter project.
    
    publish_to: "none"
    
    version: 1.0.0+1
    
    environment:
      sdk: ">=2.19.3 <3.0.0"
    
    dependencies:
      cupertino_icons: ^1.0.2
      flutter:
        sdk: flutter
      flutter_svg: ^1.0.1
      flutter_svg_provider: ^1.0.3
    
    dev_dependencies:
      flutter_lints: ^2.0.0
    
    flutter:
      assets:
        - assets/sample_bg.svg
    
      uses-material-design: true
    

    You can replace sample_bg.svg with your svg.

    Output:

    enter image description here