Adding background in flutter - flutter

What should I do to apply my background image in my project? Did I miss something? My background image found under lib/assets/background.jpg
void main() async {
WidgetsFlutterBinding.ensureInitialized();
Util flameUtil = Util();
await flameUtil.fullScreen();
await flameUtil.setOrientation(DeviceOrientation.portraitUp);
LangawGame game = LangawGame();
runApp(game.widget);
}
langaw-game.dart
class LangawGame extends Game {
Size screenSize;
double tileSize;
#override
void render(Canvas canvas) {
body:
Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/background.jpg"),
fit: BoxFit.cover,
),
),
);
}
#override
void update(double t) {}
#override
void resize(Size size) {
super.resize(size);
screenSize = size;
tileSize = screenSize.width / 9;
}
}
This is the result
This is the background
i dont have error receive but the image didnt refect

Your image path is not correct. Now your image is under lib/assets folder, but you are trying to access assets/background.jpg. You need to edit with a full path like following:
AssetImage("lib/assets/background.jpg"),
Note: Also, check your pubspec.yaml file.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add Flutter specific assets to your application, add an assets section,
# like this:
assets:
- lib/assets/background.jpg
Read more from the official document.

make sure in pubspec.yaml indention is correct.
flutter
1 tab for assets:
2 tabs for -assets/
Hope this helps

Related

how to use SvgPicture.string as a imageProvider flutter

im using flutter_svg package for svg. and now i want to use a svg inside a container as decoration like this,
Container(
decoration: BoxDecoration(
image: DecorationImage(
image: SvgPicture.string(
'''<svg viewBox="...">...</svg>'''
),
),
),
)
but the problem is DecorationImage peram expecting 'ImageProvider'. how can i do this ?
i tried flutter_svg_provider but its also not working. i found this solution, but dont know how to use.
use a custom Decoration like this:
class SvgDecoration extends Decoration {
SvgDecoration.string(String rawSvg, {this.key})
: rawSvgFuture = Future.value(rawSvg);
SvgDecoration.file(File file, {this.key})
: rawSvgFuture = file.readAsString();
SvgDecoration.asset(String asset, {this.key})
: rawSvgFuture = rootBundle.loadString(asset);
final Future<String> rawSvgFuture;
final String? key;
#override
BoxPainter createBoxPainter([ui.VoidCallback? onChanged]) {
return _SvgDecorationPainter(rawSvgFuture, onChanged, key);
}
}
class _SvgDecorationPainter extends BoxPainter {
_SvgDecorationPainter(this.rawSvgFuture, ui.VoidCallback? onChanged, String? key) {
rawSvgFuture
.then((rawSvg) => svg.fromSvgString(rawSvg, key ?? '(no key)'))
.then((d) {
drawable = d;
onChanged?.call();
});
}
final Future<String> rawSvgFuture;
DrawableRoot? drawable;
#override
void paint(ui.Canvas canvas, ui.Offset offset, ImageConfiguration configuration) {
if (drawable != null) {
canvas
..save()
..translate(offset.dx, offset.dy);
drawable!
..scaleCanvasToViewBox(canvas, configuration.size!)
..draw(canvas, offset & configuration.size!);
canvas.restore();
}
}
}
as you can see there are 3 constructors: SvgDecoration.string, SvgDecoration.file and SvgDecoration.asset but of course you can add some other custom constructors (like SvgDecoration.network for example)
The SvgPicture is a Widget, not an Image, which is why it can not be used as DecorationImage here. The way you can use the SvgPicture behind your Container is a Stack:
Stack(
children: [
SvgPicture.string(
'''<svg viewBox="...">...</svg>''',
(... width, height etc.)
),
Container(
child: (..., foreground widget)
),
],
)
Obviously, you have to make sure that both have the same size if you need it. But that depends on your usecase.

Flutter: Can we save a Canvas/CustomPainter to a gif or continuous pictures or event a video?

The bounty expires in 4 days. Answers to this question are eligible for a +50 reputation bounty.
Danny is looking for a canonical answer:
Is it possible to save a flutter canvas to a gif or a video? Is it possible to directly convert the canvas to a video with ffmpeg?
Thanks
Can we export custom painter used animation controller to a gif image or continuous images or event a video such as mp4 file?
Yes I did it one time (2 years ago) and I converted a Flutter Animation to a mp4 file. unfortunately I couldn't find the code. please follow the steps to make what you want.
capture your widget with RenderRepaintBoundary
https://api.flutter.dev/flutter/rendering/RenderRepaintBoundary/toImage.html
class PngHome extends StatefulWidget {
const PngHome({super.key});
#override
State<PngHome> createState() => _PngHomeState();
}
class _PngHomeState extends State<PngHome> {
GlobalKey globalKey = GlobalKey();
Future<void> _capturePng() async {
final RenderRepaintBoundary boundary = globalKey.currentContext!.findRenderObject()! as RenderRepaintBoundary;
final ui.Image image = await boundary.toImage();
final ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
final Uint8List pngBytes = byteData!.buffer.asUint8List();
print(pngBytes);
}
#override
Widget build(BuildContext context) {
return RepaintBoundary(
key: globalKey,
child: Center(
child: TextButton(
onPressed: _capturePng,
child: const Text('Hello World', textDirection: TextDirection.ltr),
),
),
);
}
}
you need to capture each frame of your Animation and save it to a directory. with special naming for example (1.png,2.png .... 1000.png)
import 'package:path_provider/path_provider.dart';
import 'dart:io';
Uint8List imageInUnit8List = // store unit8List image here ;
final tempDir = await getTemporaryDirectory();
File file = await File('${tempDir.path}/image.png').create();
file.writeAsBytesSync(imageInUnit8List);
install ffmpeg https://pub.dev/packages/ffmpeg_kit_flutter and use it to execute FFMPEG command
import 'package:ffmpeg_kit_flutter/ffmpeg_kit.dart';
FFmpegKit.execute('your command').then((session) async {
final returnCode = await session.getReturnCode();
if (ReturnCode.isSuccess(returnCode)) {
// SUCCESS
} else if (ReturnCode.isCancel(returnCode)) {
// CANCEL
} else {
// ERROR
}
});
search for a command to convert your images with ffmpeg to Gif Or Mp4 (some thing like these Example1 or Example2)
you can use screenshot library. by wrapping the parent container with Screenshot library you can convert widget to multiple images and those images can be converted to a gif but I think it is tricky, not efficient, and difficult to implement. you can give it a try.

flutter: NoSuchMethodError during debugging with breakpoints

I'm currently playing with flame, a small 2D game engine based on flutter. My code contains a rather strange Heisenbug: It works fine if you start it via run or debug. But if you set a breakpoint, it throws an error
Unhandled exception:
NoSuchMethodError: The getter 'cls' was called on null.
Although I don't think that this is related to flame, I was not able to reproduce the problem with flutter alone. So I'm including a minimal version of my flame-based code. It simply paints the phone-screen with a gray background color:
main.dart:
import 'package:flutter/material.dart';
import 'package:temp/game.dart';
void main(){
MyGame game = MyGame(); // error thrown here
runApp(game.widget);
}
game.dart:
import 'package:flame/game.dart';
import 'dart:ui';
class MyGame extends Game{
Size screenSize;
#override
void render(Canvas canvas) {
Rect screenRect = Rect.fromLTWH(0, 0, screenSize.width, screenSize.height);
Paint screenPaint = Paint();
screenPaint.color = Color.fromARGB(255, 100, 100, 100);
canvas.drawRect(screenRect, screenPaint);
}
#override
void update(double t) {
}
#override
void resize(Size size) {
super.resize(size);
screenSize = size;
}
}
If you want to run this, you also have to add flame to your pubspec:
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
flame: ^0.10.2
My bug happens everytime I set a breakpoint in the render method of MyGame and start debugging.
I can not reproduce this on flame: ^0.22.0 so you can just upgrade to that version and it should work fine.

How to test Flutter widgets on different screen sizes?

I have a Flutter widget which shows extra data depending on the screen size. Does anyone know a way of testing this widget on multiple different screen sizes?
I've had a look through the widget_tester source code but can't find anything.
You can specify custom surface size by using WidgetTester
The following code will run a test with a screen size of 42x42
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets("foo", (tester) async {
tester.binding.window.physicalSizeTestValue = Size(42, 42);
// resets the screen to its original size after the test end
addTearDown(tester.binding.window.clearPhysicalSizeTestValue);
// TODO: do something
});
}
Not sure why but solution of #rémi-rousselet didn't work for me. I've had to specify screen size using binding.window.physicalSizeTestValue and binding.window.devicePixelRatioTestValue so that output is fully deterministic
I've added a little bit more code for flutter beginners like me. Check this:
void main() {
final TestWidgetsFlutterBinding binding =
TestWidgetsFlutterBinding.ensureInitialized();
testWidgets("Basic layout test (mobile device)", (tester) async {
binding.window.physicalSizeTestValue = Size(400, 200);
binding.window.devicePixelRatioTestValue = 1.0;
await tester.pumpWidget(new MyApp());
expect(find.byType(MyHomePage), findsOneWidget);
// etc.
});
}
There is a package called device_preview that can simulate your flutter app running on different devices.
#rémi-rousselet's solution works perfectly!
In addition if you want to test an orientation change, try this:
const double PORTRAIT_WIDTH = 400.0;
const double PORTRAIT_HEIGHT = 800.0;
const double LANDSCAPE_WIDTH = PORTRAIT_HEIGHT;
const double LANDSCAPE_HEIGHT = PORTRAIT_WIDTH;
final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();
await binding.setSurfaceSize(Size(PORTRAIT_WIDTH, PORTRAIT_HEIGHT));
await tester.pumpWidget(MyWidget());
// test in portrait
await binding.setSurfaceSize(Size(LANDSCAPE_WIDTH, LANDSCAPE_HEIGHT));
await tester.pumpAndSettle();
// OrientationBuilder gets triggered
// test in landscape
Currently the safest way is to use setSurfaceSize
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets("foo", (tester) async {
tester.binding.setSurfaceSize(Size(400, 400));
// reset
tester.binding.setSurfaceSize(null);
// continue
});
}
See here for related Github issue
You could try this widget to test your widgets changing screen size in realtime
Screen Size Test
https://pub.dev/packages/screen_size_test
Preview
Demo
https://dartpad.dartlang.org/43d9c47a8bf031ce3ef2f6314c9dbd52
Code Sample
import 'package:screen_size_test/screen_size_test.dart';
...
MaterialApp(
title: 'Demo',
builder: (context, child) => ScreenSizeTest(
child: child,
),
home: Scaffold(
body: ListView(
children: List.generate(
20,
(index) => Container(
padding: EdgeInsets.all(10),
child: Placeholder(),
)),
),
),
)
Although #Rémi Rousselet's answer was very helpful it didn't completely solve my problem. It turns out that I could just wrap my widget under test in a MediaQuery widget and set the size.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
Widget makeTestableWidget({Widget child, Size size}) {
return MaterialApp(
home: MediaQuery(
data: MediaQueryData(size: size),
child: child,
),
);
}
testWidgets("tablet", (tester) async {
final testableWidget = makeTestableWidget(
child: WidgetUnderTest(),
size: Size(1024, 768),
);
...
});
testWidgets("phone", (tester) async {
final testableWidget = makeTestableWidget(
child: WidgetUnderTest(),
size: Size(375, 812),
);
...
});
}

flutter download an Image from url

I'm trying to load image from server using networkimage() and I want to download the same once it is loaded.. can anyone suggest me some ideas.
CircleAvatar(
backgroundImage: NetworkImage(url),
maxRadius: 15.0,
);
Here I'm loading image from my server. I want to save to the image to particular path after the image is loaded.
I recently battled this, and decided to solve it without plugins. I hope it helps someone.
The below program downloads a picture from the web, stores it in the device's local path, and then displays it when run. (note, it does not work for flutter web because you don't have access to the local file storage on that platform. Instead you would have to save the image to a local database using a plugin like sqflite, or hive from pub.dev.) Here's the code:
import 'package:flutter/material.dart';
import 'package:http/http.dart' show get;
import 'dart:io';
import 'package:path_provider/path_provider.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Test Image',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Test Image'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
initState() {
_asyncMethod();
super.initState();
}
_asyncMethod() async {
//comment out the next two lines to prevent the device from getting
// the image from the web in order to prove that the picture is
// coming from the device instead of the web.
var url = "https://www.tottus.cl/static/img/productos/20104355_2.jpg"; // <-- 1
var response = await get(url); // <--2
var documentDirectory = await getApplicationDocumentsDirectory();
var firstPath = documentDirectory.path + "/images";
var filePathAndName = documentDirectory.path + '/images/pic.jpg';
//comment out the next three lines to prevent the image from being saved
//to the device to show that it's coming from the internet
await Directory(firstPath).create(recursive: true); // <-- 1
File file2 = new File(filePathAndName); // <-- 2
file2.writeAsBytesSync(response.bodyBytes); // <-- 3
setState(() {
imageData = filePathAndName;
dataLoaded = true;
});
}
String imageData;
bool dataLoaded = false;
#override
Widget build(BuildContext context) {
if (dataLoaded) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image.file(File(imageData), width: 600.0, height: 290.0)
],
),
),
);
} else {
return CircularProgressIndicator(
backgroundColor: Colors.cyan,
strokeWidth: 5,
);
}
}
}
pubspec.yaml file:
http: ^0.12.1
path_provider: ^1.6.5
flutter version: 1.20.0-3.0.pre.112
dart version 2.9.0-19.0.dev
I recommend image_downloader.
For ios, image is saved in Photo Library.
For Android, image is saved in Environment.DIRECTORY_DOWNLOADS or specified location. By calling inExternalFilesDir(), specification of permission becomes unnecessary.
By callback(), you can get progress status.
The following is the simplest example. It will be saved.
await ImageDownloader.downloadImage(url);
I used image_downloader.
Use await ImageDownloader.downloadImage("url") of image_downloader package's method to download image using it's url.
Note : above method will return value as follows :-
imageId of the saved image if saving succeeded.
null if not been granted permission.
for this you have to ask for storage permission, just add following line into android manifest file :
uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
Otherwise it is a PlatformException.
I tried many solution, but this is simplest solution for my... Just try it
STEP - 1
Add this package in your pubspec.yaml file
dependencies:
image_downloader: ^0.20.1
STEP - 2
Add this in your dart file
import 'package:image_downloader/image_downloader.dart';
STEP - 3
Write this code on press download button
ColButton(
title: 'Download',
icon: Icons.file_download,
onTap: () async {
try {
showLoadingDialog(context);
// Saved with this method.
var imageId =
await ImageDownloader.downloadImage("https://raw.githubusercontent.com/wiki/ko2ic/image_downloader/images/bigsize.jpg");
if (imageId == null) {
return;
}
// Below is a method of obtaining saved image information.
var fileName = await ImageDownloader.findName(imageId);
var path = await ImageDownloader.findPath(imageId);
var size = await ImageDownloader.findByteSize(imageId);
var mimeType = await ImageDownloader.findMimeType(imageId);
Navigator.pop(context);
showToast('Image downloaded.');
} on PlatformException catch (error) {
print(error);
}
},
),
I use this plugin to save image in the phone using an URL
https://pub.dartlang.org/packages/image_picker_saver
For more advanced handling of Image/File downloads, you can consider the flutter_downloader package.
Some of the features that I like are :
Shows OS level download progress
can track all downloads
Has notification