Checking if AssetImage asset path exist - flutter

How do I load AssetImage or check if it exists? The data is coming from the api, so I cannot list all the file paths as constants.
As an example path maybe be 'assets/images/${card.imageType}.png' where card.inageType is a variable.
...
child: Image(
height: 60.0,
image: Utils.getImage('assets/images/card-${card.category}.png'),
),
...
For my getImage function, I tried 2 kinds but not working
Method 1: Using File: The existsSync method is always false. Keep in mind the await async cannot work as the Image widget is expecting not a Future
static dynamic getImage(path) {
File f = File(path);
return f.existsSync()
? FileImage(f)
: const AssetImage('assets/images/default.png');
}
}
Method 2: Using try catch: The exceptions is not being caught
static AssetImage getImage(path) {
AssetImage image;
try {
image = AssetImage(path);
} catch (e) {
image = const AssetImage('assets/images/default.png');
}
return image;
}

You can use something like this to check if an asset exists:
// example: 'assets/check_green.png'
Future<bool> checkIfAssetExists(String fullAssetPath) async {
final Uint8List encoded = Utf8Codec()
.encoder
.convert(Uri(path: Uri.encodeFull(fullAssetPath)).path);
// returns null if an asset is not found
final ByteData? asset = await ServicesBinding.instance!.defaultBinaryMessenger
.send('flutter/assets', encoded.buffer.asByteData());
return asset != null;
}
You can run this in your initState and then use AssetImage confidently.
As for the exception not being caught, it probably means than an Error was throw which is different from Exceptions

You can check if a file exists asynchronously with this code:
import 'dart:io';
File("path/to/file").exists()
or checking it synchronously:
import 'dart:io';
File("path/to/file").existsSync()
Update:
isPathExists() function is called from initState.
AssetBundle is used for to obtain asset inside asset folder. You can insert anything to menubanner.png if it exists, the image will be assigned to variable and if it does not, an exception throws.
late Image image;
isPathExists() async {
try {
var assetbundle = DefaultAssetBundle.of(context);
ByteData res = await assetbundle.load('assets/images/menubanner.png');
var list = Uint8List.sublistView(res);
setState(() {
image = Image.memory(list);
});
} catch (exception) {
print(exception);
}
}

You can not use Asset Image for images fetched from Network.
Once you get response from your api. Store the url of the image in a String variable. Usually images from API are stored in a web service.
When you have the url of the image just use NetworkImage widget, example:
SizedBox(
width: 75,
height: 75,
child: userImgUrl.isEmpty
? const CircleAvatar(
child: Text('Avatar'))
: CircleAvatar(
radius: 30,
backgroundImage: NetworkImage(
userImgUrl),
backgroundColor: Colors.transparent),)
Think userImgUrl is the String that holds the url for the image that can be found on the internet. If image is empty just show a text inside circle avatar. If image is available from API, then show the image inside NetworkImage()

Related

flutter image_web_picker Object? instead of Image returned

I copied this from the official image web picker files but I get the message that getImage return an Object? instead of an Image. Where is the problem? And I importet the package if you think that is the problem.
class _LoadPhotoState extends State<LoadPhoto> {
late final Image _pickedImage;
Future<void> _pickImage() async {
Image fromPicker = await ImagePickerWeb.getImage(outputType: ImageType.widget);
setState(() {
_pickedImage = fromPicker;
});
}
}
It's not your fault, the README is wrong: the API reference of that package says the getImage method returns a Future<Object?>. However, the solution is easy:
Image fromPicker = (await ImagePickerWeb.getImage(outputType: ImageType.widget)) as Image;

Unable to load pdf from url using Syncfusion_flutter_pdf

I am working on an application that requires me to load pdf from url. The plugin I am using is syncfusion_flutter_pdf. I couldn't find a direct way to do the same so I tried downloading the file first and then use it. But the pdf is not displaying for some reason! There were nothing in the logs. Can you guys please tell me what went wrong?
fileDownload() async {
tempDir = await getApplicationDocumentsDirectory();
tempPath = tempDir.path + 'flutter-succinctly.pdf';
final dio = Dio();
if (await File(tempPath).exists()) {
//print('tempPath exists at: $tempPath');
if (await File(tempPath).length() == 0) {
dio.download(
'https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf',
tempPath,
);
} else {
_readPDF();
}
} else {
print('path does not exist');
dio.download(
'https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf',
tempPath);
}
}
Future<void> _readPDF() async {
final PdfDocument document =
PdfDocument(inputBytes: File(tempPath).readAsBytesSync());
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextButton(
child: const Text('Generate PDF'),
style: TextButton.styleFrom(
primary: Colors.white,
backgroundColor: Colors.lightBlue,
onSurface: Colors.grey,
),
onPressed: fileDownload,
)
],
),
));
}
We do not have direct support to load PDF from URL. We can load and read PDF data by using http package. We have created a sample to read the PDF data from webspace/website to load and save it using the retrieved PDF data. Kindly try the following code example and sample in your side,
Add http package in dependencies section of pubspec.yaml file
dependencies:
http: ^0.13.3
Import the following package in your dart file.
//Read an PDF data from website/webspace
import 'package:http/http.dart' show get;
Get image data
//Read an PDF data from website/webspace
var url = "https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf";
var response = await get(Uri.parse(url));
var data = response.bodyBytes;
Load data into PDF document
//Create a new PDF document
PdfDocument document = PdfDocument(inputBytes: data);
//Save PDF document
final List bytes = document.save();
//Dispose the document.
document.dispose();
Please find the sample from https://www.syncfusion.com/downloads/support/directtrac/general/ze/pdf_sample565926150.

How to convert a Image file to Asset Image in flutter?

I am using the image_picker and image_cropper plugin to select or capture the image with the help of the camera and Gallery. I got an image file from an image_picker. Now, I am using the Image.asset() widget to show the image in the Circle Avatar. Can anyone please tell me how I convert an image File to an asset image?
My code:
//Function that decides if image is returned or not(If not, then it will show the default circle avator)
File getImageWidget() {
if (_selectedImage != null) {
return _selectedImage;
} else {
return null;
}
}
//Function to set the image in the circle avatar
circleAva(){
return profileIconSelector(
setProfileIconHighQuality(getImageWidget() ?? userDetails.profile_pic,
userDetails.loginInitFrom),
userDetails.name,
SizeConfig.heightMultiplier * 5);
}
//Function to get image from Camera or Gallery
getImage(ImageSource source) async {
this.setState((){
_inProcess = true;
});
File image = await ImagePicker.pickImage(source: source);
if(image != null){
File cropped = await ImageCropper.cropImage(
sourcePath: image.path,
aspectRatio: CropAspectRatio(
ratioX: 1, ratioY: 1),
compressQuality: 100,
maxWidth: 700,
maxHeight: 700,
compressFormat: ImageCompressFormat.jpg,
androidUiSettings: AndroidUiSettings(
toolbarColor: Colors.deepOrange,
toolbarTitle: "Cropper",
statusBarColor: Colors.deepOrange.shade900,
backgroundColor: Colors.white,
)
);
this.setState((){
_selectedImage = cropped;
_inProcess = false;
});
} else {
this.setState((){
_inProcess = false;
});
}
}
You can't add asset images from your app. Asset images are images that you add to your project manually, but you can save the path to the image once it has been picked, then use Image.file(File.fromUri(Uri.file(IMAGE_PATH))).
Fortunately, I found the solution for this by myself.
In the case of the Image.file() widget, we have to provide the image of a File type.
And, In the case of the AssetImage() or Image.asset() widget, we need to pass the image path of String type.
So the Solution to use Image of File type in AssetImage() or
Image.asset() widget:
File _selectedImage = fetchedFromCameraOrGallery;
getImageWidget() {
if (_selectedImage != null) {
return CircleAvatar(
radius: SizeConfig.heightMultiplier * 5,
backgroundImage: AssetImage(
_selectedImage.path, //Convert File type of image to asset image path
),
);
}
}
We have to simply use the _selectedImage.path that will convert the image file of File type to a valid Asset image path format.

Getting a "File$" instead of a File in flutter

I am allowing users to grab a profile pic and upload that picture as file to my server, but I'm getting this error when inputting the image via ImagePickerWeb:
<error>:<getObject: Unexpected error from chrome devtools:>
I don't know if it's my browser or me, but this is what I'm trying:
Future<void> getMultipleImageInfos() async {
var imageFile =
await ImagePickerWeb.getImage(outputType: ImageType.file);
print(imageFile);
if (imageFile != null) {
setState(() {
currentSelfie = imageFile;
_accDetails['customer_selfie'] = currentSelfie;
});
}
}
Then displaying that photo here:
Image.file(
currentSelfie,
height: screenAwareSize(100, context),
width: screenAwareSize(100, context),
fit: BoxFit.fill,
)

Flutter error while showing profile picture google play games

Using the play_games extension, I'm having trouble returning the user's profile image.
Use the method below to login and set the state with the return of the user's data.
Image provider: NetworkImage ("content: //com.google.android.gms.games.background/images/f56551ac/42", scale: 1.0)
// Google Play Games stance
final GameServices gameservices = GameServices();
Account profile;
ui.Image profileimage;
void _login() async {
final res = await gameservices.login();
final resimage = await res.hiResImage;
setState(() {
profile = res;
profileimage = resimage;
});
print(profileimage);
}
In the widget I'm in the form of NetworkImage, but it's still not rendering on the screen.
this error: The argument type 'Image' can't be assigned to the parameter type 'String'.
Container(
width: 128,
height: 128,
padding: EdgeInsets.all(8),
child: CircleAvatar(
backgroundImage: NetworkImage(this.profileimage != null ? this.profileimage : 'https://api.adorable.io/avatars/128/')
),
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.circle
),
),
[ RESOLVED!!! ]
Change my code and play_games returns type vars.
Lets go:
Future<Uint8List> get hiResImage async =>
await _fetchToMemory(await _channel.invokeMethod('getHiResImage'));
Future<Uint8List> get iconImage async =>
await _fetchToMemory(await _channel.invokeMethod('getIconImage'));
}
Future<Uint8List> _fetchToMemory(Map<dynamic, dynamic> result) {
Uint8List bytes = result['bytes'];
if (bytes == null) {
print('was null, mate');
return Future.value(null);
}
// Completer<Image> completer = new Completer();
// decodeImageFromList(bytes, (image) => completer.complete(image));
return Future.value(bytes);
}
And my code, only this change:
Uint8List profileimage;
Flutter is yelling at you because you gave it a URL with protocol content://, when it expects http:// or https:// for a NetworkImage widget. See documentation at: https://flutter.dev/docs/cookbook/images/network-image
This happen because google provide encoded image. In android we can use ImageManager for that as google suggest.
In flutter there are mechanism for getting Future<Image> from hiresImageUri. Check here.
Use Something like below,
profile.hiResImage.then((Image result){
//here you can get image in result
});