is it possible change asset docx file and reopen it in flutter - flutter

I used path-provider and open-file for open docx file from asset which worked fine without conflict in my project, then I needed to change some text in docx file. After changing it gave me an error like
Unable to open the document, decoding error
here is my open file method code
onPressed: () async {
Future<File> openFileFromAsset() async {
Directory tempDir = await getTemporaryDirectory();
File tempFile = File('${tempDir.path}/$fileName.docx');
ByteData bd = await rootBundle.load(assetName);
await tempFile.writeAsBytes(bd.buffer.asUint8List(), flush: true);
return tempFile;
}
openFileFromAsset().then((file){OpenFile.open(file.path);});
},
I want to fix the error

Related

flutter_downloader auto open file when complete

so I'm trying to work with download manager in flutter using flutter_downloader package. I manage to make my app download the file I wanted. How can I make my app more advance ? I wanted my app to be able to open the downloaded file automatically when the download is done.
Another question is, if I already download the file first time how can I make the button trigger to open the file location rather than downloading the file again ?
Here's my current code:
TextButton(
child: Text(
ticketData['file_attachment_map'][index]['name'],
style: primaryColor600Style.copyWith(fontSize:14.sp),
),
onPressed: () async {
final permissionStatus = await Permission.storage.request();
if (permissionStatus.isGranted) {
final externalDir = await getExternalStorageDirectory();
final taskId =await FlutterDownloader.enqueue(
url: ticketData['file_attachment_map']
[index]['url'],
savedDir:externalDir!.path,
showNotification:true,
openFileFromNotification:true,
);
} else {
print('Permission denied');
}
},
),
Use open_file package after downloaded
if(taskId != null){
await OpenFile.open(filePath);
}
}
And you can check file exist before download file
import 'dart:io';
File("path/to/file").exists()
As a complement to #Xuann Thucc answer, you can use the open_filex which is a fork of open_file but is better maintained and fixes many issues with the original lib.
import 'package:open_filex/open_filex.dart';
// in async function
await OpenFilex.open(filePath);

Flutter passing image string

i'm trying to send an image on instagram using flutter with the social_share package.
My issue is that i'm new with flutter and i don't find a proper way to send a path to the function SocialShare.shareInstagramStory(imageFile.path, "#ffffff", "#000000", "https://deep-link-url");
My images are located in the root of the flutter project in assets/images/my_images.
When i try to put the path SocialShare.shareInstagramStory("assets/images/my_image.jpeg");
i guess the phone doesn't know this path since it's looking on his own directory
hope i'm clear enough and thanks for your time!
Edit : here's my code:
onPressed: () async {
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
File file = File(tempDir.path);
final byteData = await rootBundle.load('assets/images/img_1.jpeg');
await file.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
await SocialShare.shareInstagramStory(file.path);
Navigator.of(context).pop();
},
i got this error :
E/flutter (12761): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: FileSystemException: Cannot open file, path = '/data/user/0/com.example.app/cache' (OS Error: Is a directory, errno = 21)
So basically, what you need to do is convert your asset image into a file, then create a temporary path and store this file there. Then you can reference that path
We need to create a temporary path with this plugin https://pub.dev/packages/path_provider
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
Then create a file
File file = File(tempDir.path+'/img_1.jpeg');//You might have to play arounf with the /. Remove it or put it in the end to see what works
Now we need to write the image to this
final byteData = await rootBundle.load('assets/images/img_1.jpeg');
await file.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
Now you can use this temporary path to do what you want

flutter path_provider could not read downloaded files

I am using path_provider on flutter and would like to build Download file(mp4&jpg, from aws S3) and play it. I succeeded download and confirmed file is downloaded.(on ios)
But, when access the files using path_provider, raised error like below.
Unable to load asset: /Users/username/Library/Developer/CoreSimulator/Devices/B78BC67E-B127-4DD0-8A42-965EE645157B/data/Containers
the saving method is below
Future<File> _getFile(String filename) async {
final dir = await getApplicationDocumentsDirectory();
return File("${dir.path}/$filename");
}
final file = await _getFile("filename");
file.writeAsBytes(Bytes);
and the load method is below
final directory = await getApplicationDocumentsDirectory();
.
.
.
Image(image: AssetImage('${directory.path}/filename')) // /Users/username/Library/Developer/CoreSimulator/Devices/B78BC67E-B127-4DD0-8A42-965EE645157B/data/Containers/Data/Application/46EF23F5-840C-47D4-8314-B97CDEE2198C/Documents
.
.
.
Actually I need to use FileImage instead of Asset.
Thanks for GrahamD

How do you download an image from the internet onto a file in Flutter?

I'm making a Flutter project where an image is displayed in listview and the user can share, favourite or download the image. I'm stuck on the downloading part. Is it possible to save an image file onto the phone's storage for offline use?
What I want to happen is I can create and write an image file
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/$title.txt');
}
// Write an image by obtaining an image through a URL
and then be able to access it through
Image.file('$path/$title.txt')

Unable to load asset in Flutter

I'm sharing a picture that I've taken previously with the camera using image_picker. It works fine on the emulator but not on my device:
onPressed: () async {
ByteData image = await rootBundle.load(team.avatar.path);
...
},
This is the error with the path:
Unable to load asset:
/storage/emulated/0/Android/data/drodriguez.apps.Words/files/Pictures/scaled_2eccad3d-382e-462e-b124-b8fa06a2a32b791445736175256137.jpg
The image is being shown without errors so the path is 100% correct:
Image.file(
_orderedTeams[index].avatar,
fit: BoxFit.cover,
height: 92.0,
width: 92.0,
)
Do I need to add something else maybe on the pubspec.yml?
You can't use the rootBundle to access files on the phone. The rootBundle (as said in its docs) only works for files packaged with the application when was built (probably saved on assets, declared on pubspec, etc).
If you want to load an image from the phone, this maybe help.
ANSWER
This function can read a filePath and return a Uint8List (a byteArray):
Future<Uint8List> _readFileByte(String filePath) async {
Uri myUri = Uri.parse(filePath);
File audioFile = new File.fromUri(myUri);
Uint8List bytes;
await audioFile.readAsBytes().then((value) {
bytes = Uint8List.fromList(value);
print('reading of bytes is completed');
}).catchError((onError) {
print('Exception Error while reading audio from path:' +
onError.toString());
});
return bytes;
}
And, to get a ByteData just:
var path = 'Some path to an image';
var byteArray = _readFileByte(path);
ByteData data = ByteData.view(byteArray.buffer);
(The answer is based on this)