Dislaying Image File in Container Exported From Video - flutter

Trying to export a frame from my video file, save it to an image file list, and then display it back when building my list of containers.
setState(() async{
if (result!.files.isNotEmpty) {
for (PlatformFile item in result.files) {
videos.add(File(item.path!));
var duration = Duration(seconds: 1);
File image = await ExportVideoFrame.exportImageBySeconds(File(item.path!), duration, 0);
videoThumbs.add(image);
//tickets[widget.indexEvent].videos[i]
}
} else {}
});
Then later in my page class I am trying to display it back for the user in a child of my container:
Container(
width: 220,
height: 220,
color: colorPrimary,
child: Image.file(
videoThumbs[i],
width: 100,
height: 100,
fit: BoxFit.fill,
),
),
The code doesn't hard fail, and will build the apk, but when in the app, my thumbnail just says:
As you can see from my thumbnail, my list of photos and videos are building, but when it tries to loop through the videos and show a thumb, the array index is empty, I think? I believe I'm reading that error right.
I have seriously been at this for 2 weeks, and I could really use some help.

in this list, Your data is not complete, on 2 last of your data is null.
use this:
child:
videoThumbs[I] == null? const SizedBox():
Image.file(
videoThumbs[i],
width: 100,
height: 100,
fit: BoxFit.fill,
),

Related

Storing base 64 locally and use it offline

I have a 64 base image that am getting from my database , which I want to store locally and reuse offline. am using local storage package , the image works perfectly fine when I call it online but fades away offline . here is where am storing it :
String baseUrl = await GetSharedPrefs.getBaseURl();
_imageLogoPath =
(await SettingsServices().fetchLogoImage(baseUrl: baseUrl, id: 1));
storage.setItem('logoImage', _imageLogoPath);
notifyListeners();
and this is where am calling it :
class _LogoViewState extends State<Logo> {
void initState() {
Provider.of<SettingsViewModel>(context, listen: false).fetchLogoPath();
super.initState();
}
#override
Widget build(BuildContext context) {
final LocalStorage storage = new LocalStorage('deepnrise');
var settings = Provider.of<SettingsViewModel>(context);
String? image = settings.imagepath;
int i = 1;
String im = storage.getItem('logoImage');
if (im!.isNotEmpty) {
i +=1;
print("soy image $im");
final UriData? data = Uri.parse(im).data;
print(image);
Uint8List? myImage = data?.contentAsBytes();
return Padding(
padding: EdgeInsets.all(10.0),
child: ClipRRect(
borderRadius: BorderRadius.circular(15),
child: Image.memory(
myImage!,
fit: BoxFit.contain,
width: 50,
)),
);
} else if (im.isEmpty || im == null) {
return Padding(
padding: EdgeInsets.all(16.0),
child: ClipRRect(
borderRadius: BorderRadius.circular(15),
child: Image.asset(
"assets/images/deepn.png",
fit: BoxFit.contain,
width: 35,
)),
);
}
return Padding(
padding: EdgeInsets.all(16.0),
child: ClipRRect(
borderRadius: BorderRadius.circular(15),
child: Image.asset(
"assets/images/deepn.png",
fit: BoxFit.contain,
width: 35,
)),
);
}
}
every time I get a null exception (null is not subtype of type string) , so I tried to call my provider in another widget , which resulted in the image fading away when offline . I want to be able to call the image from local storage , when off/ online . I have tried shared preferences package and the same thing happens if anyone please know how to help don't hesitate thanks in advance.

Upload multiple file to fire store with progress bar in flutter

I would like to upload more than one file to fire-store while showing a progress indicator. Am trying to achieve this by looping over the files chosen by the user. The files are picked using the flutter filePicker package.
for (var file in choosenFiles) {
String fileName = file.name;
String? filePath = file.path;
File creatFile = File(filePath!);
UploadTask task = FirebaseStorage.instance
.ref('post_files/${value.id}-$fileName')
.putData(creatFile.readAsBytesSync());
task.snapshotEvents.listen((event) {
setState(() {
progress = ((event.bytesTransferred.toDouble() /
event.totalBytes.toDouble() *
100)
.roundToDouble());
});
});
}
for the progress indicator, i use a circularProgressIndicator to listen to the value of variable progress.
Center(
child: SizedBox(
height: 100,
width: 100,
child: CircularProgressIndicator(
value: progress / 100,
backgroundColor: Colors.green,
color: Colors.red,
strokeWidth: 8,
),
),
)
What could be the problem?. Will be grateful for any help. thanks.

Firestore databse, upload and download files

I want to create button which will allow me to upload images to specific database collection, I manually created a collection and added some random pictures there which I'm using for slider in the app.
Here is code for fetching them from this database:
initSliderImages() async {
var result = await FirebaseFirestore.instance.collection('slider_images');
result.snapshots().listen((data) {
List imgs = [];
data.docChanges.forEach((change) {
var imageData = change.doc.data();
String image = imageData['url'];
imgs.add(CachedNetworkImage(fit: BoxFit.cover, imageUrl: image));
});
setState(() {
images = imgs;
});
});
}
And here is Slider code:
sList images = [];
Widget slider() {
return Container(
child: SizedBox(
height: 200.0,
width: fullWidth(context),
child: (images != null && images.length > 0)
? Carousel(
images: images,
dotSize: 3.0,
dotSpacing: 10.0,
dotColor: Colors.red,
indicatorBgPadding: 5.0,
dotBgColor: Colors.grey.withOpacity(0.5),
// dotBgColor: Colors.transparent,
borderRadius: true,
moveIndicatorFromBottom: 180.0,
noRadiusForIndicator: true,
)
: JumpingDotsProgressIndicator(
fontSize: 40.0,
color: Colors.blue,
),
),
);
}
So I want to create button which will alow me to upload images to this database collection, and also to alow me to remove them from database collection, maybe in some other page to create grid view which will display images from this database collection, and to be able to remove image from them.

Show picture from assets or from files Flutter

I want to show a picture inside a CircleAvatar, if the user never inserted a picture before then the default picture "empty_profile.png" will appear, otherwise if the user already inserted a picture from gallery or camera then the last one will be shown.
This is the code :
File _file = null;
File variable declared at the beginning.
Future<void> changeImage() async { //This will change the picture
File tmp = await imgFromGallery();
setState(() {
_file = tmp;
});
return;
}
The function above will change _file value to the file picked from gallery.
Widget myAvatar() {
return GestureDetector(
onTap: null,
child: CircleAvatar(
radius: 55,
backgroundColor: Color(0xffFDCF09),
child: CircleAvatar(
radius: 50,
child: Container(
child: _file == null
? AssetImage("empty_profile.png")
: FileImage(_file),
),
),
),
);
}
Finally if file is still null then the asset image is loaded, otherwise if a new picture is choosen then FileImage(_file) will show the picked image.
I have a lots of error because I don't know very well how to handle files, their paths and show images...Can you explain me how I should do?
To include static images in your Flutter project, place them inside the "assets/images" folder. Then, make sure to add this folder to your pubspec.yml:
flutter:
assets:
- assets/images/
Next, you may have errors related to trying to render an AssetImage inside a CircleAvatar. To render the file as an Image widget instead, use Image.asset(<path>). Your example could be written as:
Widget myAvatar() {
return GestureDetector(
onTap: null,
child: CircleAvatar(
radius: 55,
backgroundColor: Color(0xffFDCF09),
child: _file == null
? Image.asset("assets/images/empty_profile.png")
: _file
),
);
}
Finally, a great resource for user-selected images is the image_picker library: https://pub.dev/packages/image_picker. For example, a "Select from Gallery" button could invoke the following code, which allows the user to crop the image and saves it as an Image widget:
PickedFile image = await picker.getImage(
source: ImageSource.gallery, // to select from camera, use ImageSource.camera
maxHeight: 1024,
maxWidth: 1024,
imageQuality: 50
);
try {
File croppedImage = await ImageCropper.cropImage( // use platform-native image cropping
sourcePath: image.path,
cropStyle: CropStyle.circle,
maxWidth: 512,
maxHeight: 512
);
setState(() { // refresh state to render new profile image
_file = Image.file(croppedImage)
})
} catch (err) {
print(err)
}
You can use CachedNetworkImage PlugIn - Update other details as per your need. This code show Network Images, if not available will show Assets Image.
new Container(
width: 140.0,
height: 140.0,
child: ClipOval(
child: CachedNetworkImage(
imageUrl: _profile == null ? "" : Api.baseURL + _profile,
placeholder: (context, url) =>
Center(child: CircularProgressIndicator()),
errorWidget: (context, url, error) => Image.asset(
"img/user.png",
fit: BoxFit.cover,
height: 140.0,
width: 140.0,
),
fit: BoxFit.cover,
height: 140.0,
width: 140.0,
),
),
),

onError method of DecorationImage() in Flutter

Code works fine but because of my unreliable internet connection I am faced with an issue of NetworkImage.load ( See error image below )
Container(
width: 60,
height: 80,
decoration: BoxDecoration(
color: Colors.black12,
borderRadius: BorderRadius.all(Radius.circular(7.0))
image: DecorationImage(
image: NetworkImage(trend['imageUrl']),
onError: <how we can handle this?>,
fit: BoxFit.cover
),
),
);
I hope this issue can be fixed by handling it on onError method (Correct me if I'm wrong). But I can't figure it out how to do that.
Error:
First of all lets say you intialize NetworkImage inside your class. like:
var imgVariable = NetworkImage(trend['imageUrl']);
Then, load your network image. If, error occurs then we will load from our assets to let user know that we could not load network image.
Container(
width: 60,
height: 80,
decoration: BoxDecoration(
color: Colors.black12,
borderRadius: BorderRadius.all(Radius.circular(7.0))
image: DecorationImage(
image: imgVariable,
onError: (errDetails){
setState(){
imgVariable = AssetImage('assets/could_not_load_img.jpg');
};
},
fit: BoxFit.cover
),
),
);
Here, assets/could_not_load_img.jpg is image that is imformative sthg.
*Note: This may not seem to work with errors, but this can be a way I came up with. There are plugins like cached_network_image to work beautifully on network images.
The accepted solution by Biplove doesn't seem to work anymore, at least I couldn't solve the resulting cast error when replacing the NetworkImage with an AssetImage. But a similar way would be:
class _YourClassState extends State<YourClass> {
bool networkError = false;
NetworkImage backgroundImage = const NetworkImage(
'youUrl');
AssetImage backgroundImageFallback = AssetImage('assets/img/....jpg');
...
decoration: !networkError ? DecorationImage(
fit: BoxFit.fill,
onError: (Object e, StackTrace? stackTrace) {
log("Could not load the network image, showing fallback instead. Error: ${e.toString()}");
if (stackTrace != null) {
log(stackTrace.toString());
}
setState(() {
networkError = true;
});
},
image: backgroundImage) :
DecorationImage(
fit: BoxFit.fill,
image: backgroundImageFallback)
}
so, onError in flutter basically takes a return type of function
it takes some error that may generate during the loading/fetching of the response image URL as the parameter Error that is generated during call and a report that provides information about program subroutines that can be found in the debug console as well
onError:(error, stackTrace) => AssetImage('assets/could_not_load_img.jpg'),
or you can check these
[click]https://github.com/flutter/flutter/issues/78925#issuecomment-806553363
[click]https://github.com/flutter/flutter/issues/78925