xxxxxxxxxx
1. add the following codes to 【pubspec.yaml】
____________________________________________________________________________________
assets:
- assets/xxx/xxx/xxx.jpg
____________________________________________________________________________________
2. call assets with the following code
AssetImage('assets/xxx/xxx/xxx.jpg')
eg : CircleAvatar(
radius: 50,
backgroundImage: AssetImage('assets/images/app_logo/guest.jpg'),)
____________________________________________________________________________________
xxxxxxxxxx
Widget build(BuildContext context) {
return Image(image: AssetImage('graphics/background.png'));
}
xxxxxxxxxx
import 'dart:async';
import 'dart:io';
import 'package:flutter/services.dart' show rootBundle;
import 'package:path_provider/path_provider.dart';
Future<File> getImageFileFromAssets(String path) async {
final byteData = await rootBundle.load('assets/$path');
final file = File('${(await getTemporaryDirectory()).path}/$path');
await file.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
return file;
}
File f = await getImageFileFromAssets('images/myImage.jpg');
xxxxxxxxxx
import 'package:flutter/material.dart';
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Image.asset('assets/images/my_image.png'),
),
),
);
}
}
xxxxxxxxxx
Image.asset(name) is essentially Image(image: AssetImage(name)),
Image.file(path) is essentially Image(image: FileImage(File(path))),
Image.network(url) is essentially Image(image: NetworkImage(url)),
Image.memory(list) is essentially Image(image: MemoryImage(list))
xxxxxxxxxx
*Note:-
Very important thing to note while using asset is that:
--> In "pubspec.yaml" file:-
line with code "uses-material-design: true"
and line with code " assets:"
should lie in same column
--> example:-
# the material Icons class.
uses-material-design: true //this line
# To add assets to your application, add an assets section, like this:
assets: // and this line (in same column)
- assets/
--> Don't be oversmart and give your image name too in assets like this:-
" assets:
- assets/onePiece"
This will cause error .(Believe it) .
xxxxxxxxxx
Future<File> getImageFileFromAssets(String path) async {
final bytes = (await rootBundle.load(path));
final assetFile = File('${(await getTemporaryDirectory()).path}/$path');
await assetFile.create(recursive: true);
await assetFile.writeAsBytes(
bytes.buffer.asUint8List(bytes.offsetInBytes, bytes.lengthInBytes));
return assetFile;
}
File f = await getImageFileFromAssets("images/image.png")