Reputation: 5867
From this question I am using Flutter's SVG package (flutter_svg
) to render a SVG image.
I want to use the SVG as a Container
background with Text
in the middle.
This is the code I have so far:
Container(
decoration: BoxDecoration(
image: DecorationImage(image: SvgPicture.asset(
'assets/example.svg',
),),
),
children: <Widget>[
Text('Welcome to my Flutter App',
style: Theme.of(context).textTheme.display1.copyWith(
color: Colors.white,
fontWeight: FontWeight.bold
)
),
],
)
The problem I am finding is that SvgPicture
is not an ImageProvider
so I can't add the BoxDecoration
to get a background image.
Is there a way to then use SvgPicture
as a Container's box decoration or background?
Upvotes: 41
Views: 55980
Reputation: 3258
First of all, make sure you use presentation attributes instead of CSS when exporting/saving your SVG file. Otherwise it won't work.
Then use the 'flutter_svg_provider' package, double check that you are importing that package and not the 'flutter_svg' package, and finally create your SVG image like this: Svg('path/to/your/file.svg')
.
Now you can use that image in your boxDecoration and it should work properly.
Upvotes: 0
Reputation: 11
This worked for me
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
image: DecorationImage(
image: _getSvgImageProvider('assets/background.svg'),
fit: BoxFit.cover,
),
),
child: Center(
child: Text('Hello World'),
),
);
}
ImageProvider _getSvgImageProvider(String assetName) {
final svgString = DefaultAssetBundle.of(context).loadString(assetName);
final DrawableRoot svgDrawableRoot = SvgParser.parse(svgString);
final ui.Picture picture = svgDrawableRoot.toPicture();
final ui.Image image = picture.toImage(
svgDrawableRoot.viewport.viewBox.width.toInt(),
svgDrawableRoot.viewport.viewBox.height.toInt(),
);
final provider = MemoryImage(
Uint8List.view(image.toByteData(format: ui.ImageByteFormat.png).buffer),
);
return provider;
}
}
Upvotes: 1
Reputation: 559
The exact way to use an SvgPicture is like this:
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: <Widget>[
SvgPicture.asset(
'assets/images/splash/background.svg',
alignment: Alignment.center,
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
),
Container(
child: Column(
children: <Widget>[Expanded(child: _createLogo())],
),
),
],
),
);
}
Upvotes: 46
Reputation: 410
You can also use flutter_svg_provider
Like this :
import 'package:flutter_svg_provider/flutter_svg_provider.dart';
Container(
decoration: BoxDecoration(
image: DecorationImage(image: Svg(
'assets/example.svg',
),),
),
)
Upvotes: 11
Reputation: 1835
how about using a stack() and build everything on top of that. That is how I have done it with just an image as a background for the full viewport.
Upvotes: 22