How to add local image to flutter_local_notifications - flutter

I am trying to create push notifications and would like to add an image to the notification. I am able to add images from the web as shown in the screenshot below.
How can I add a local image instead? I tried adding the file path as shown below, but it did not work:

The file path you are adding is a root path of your project but this method needs an android file path(e.g. /storage/emulated/0/Android/data/com.expampe.app/cache/bg.png), so you have to convert your asset image to a File and save it, then return its path:
import 'dart:async';
import 'dart:io';
import 'package:flutter/services.dart' show rootBundle;
import 'package:path_provider/path_provider.dart';
Future<String> getImageFilePathFromAssets(String asset) async {
final byteData = await rootBundle.load(asset);
final file =
File('${(await getTemporaryDirectory()).path}/${asset.split('/').last}');
await file.writeAsBytes(byteData.buffer
.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
return file.path;
}
then just
final attachmentPicturePath = await getImageFilePathFromAssets('assets/image2.jpg');

The Easiest Way is--
static Future<String> getImageFilePathFromAssets(
String asset, String filename) async {
final byteData = await rootBundle.load(asset);
final temp_direactory = await getTemporaryDirectory();
final file = File('${temp_direactory.path}/$filename');
await file.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes,
byteData.lengthInBytes));
return file.path;
}
final bigpicture = await Utils.getImageFilePathFromAssets(
'assets/images/largicon.png', 'bigpicture');
And For donwload Using URL---
add http and path_provider in pubspec.yml
static Future<String> downloadFile(String URL, String filename) async
{
final direactory = await getApplicationSupportDirectory();
final filepath = '${direactory.path}/$filename';
final response = await http.get(Uri.parse(URL));
print(response);
final file = File(filepath);
await file.writeAsBytes(response.bodyBytes);
return filepath;
}
check this demo github

Related

How to save video to phone gallery - Dio/Flutter

I'm trying to save the video in the phone gallery (downloaded using dio package) To get the path, I'm using path provider package but unable to save it in the phone gallery
Here is my code
void downloadVideo() async {
var dir = await getExternalStorageDirectory();
final dio = Dio();
dio.download(
'video_url',
'${dir!.path}/video.mp4', // saving path, I'm trying to save it in phone gallery
onReceiveProgress: (actualBytes, totalBytes){
var percentage = actualBytes/totalBytes*100;
}
);
}
Note:- I'm aware of gallery_saver package but I need to achieve this using dio and path provider
So you already have the saving directory. You can use plugins like image_gallery_saver and gallery_saver to save your downloaded video to the gallery.
If you use image_gallery_saver, the saving code would be similar to this:
await ImageGallerySaver.saveFile(finalVideoPath);
And don't forget to delete the video in the download path after saving the video successfully to the gallery.
Final code:
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/widgets.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
Future<void> downloadVideo() async {
final appDocDirectory = await getAppDocDirectory();
final finalVideoPath = join(
appDocDirectory.path,
'Video-${DateTime.now().millisecondsSinceEpoch}.mp4',
);
final dio = Dio();
await dio.download(
'video_url',
finalVideoPath,
onReceiveProgress: (actualBytes, totalBytes) {
final percentage = actualBytes / totalBytes * 100;
},
);
await saveDownloadedVideoToGallery(videoPath: finalVideoPath);
await removeDownloadedVideo(videoPath: finalVideoPath);
}
Future<Directory> getAppDocDirectory() async {
if (Platform.isIOS) {
return getApplicationDocumentsDirectory();
}
return (await getExternalStorageDirectory())!;
}
Future<void> saveDownloadedVideoToGallery({required String videoPath}) async {
await ImageGallerySaver.saveFile(videoPath);
}
Future<void> removeDownloadedVideo({required String videoPath}) async {
try {
Directory(videoPath).deleteSync(recursive: true);
} catch (error) {
debugPrint('$error');
}
}

Flutter App for encryption an audio for secure

I have a project with encrypt an audio for secure my data audio and when the user purchase they can play the audio, but until now didn't find how to do that. I found another way by converting the audio data into a string and then encrypting it, I found a code but it's incomplete so I'm still confused about using it.
import 'dart:io';
import 'dart:typed_data';
import 'package:file_picker/file_picker.dart';
import 'package:path_provider/path_provider.dart';
class MediaFile {
Future<String> get docPath async {
Directory appDocDir = await getApplicationDocumentsDirectory();
return appDocDir.path;
}
Future<Uint8List> get audioFileData async {
final String path = await docPath;
final String theFilePath = '$path/test.mp3';
final File theFile = new File(theFilePath);
if (await theFile.exists()) {
return await theFile.readAsBytes();
} else {
File file = await FilePicker.getFile();
return await file.readAsBytes();
}
}
Future<String> dataToString() async {
Uint8List data = await audioFileData;
return new String.fromCharCodes(data);
}
Future<File> saveMediaAsString(String fileName, String fileContent) async {
String path = await docPath;
Directory dataDir = new Directory('$path/data');
if (await dataDir.exists()) {
File file = new File('$path/data/$fileName');
return file.writeAsString(fileContent);
}
await dataDir.create();
File file = new File('$path/data/$fileName');
return file.writeAsString(fileContent);
}
Future<String> readFromStringMediaFile(String fileName) async {
String path = await docPath;
File file = new File('$path/data/$fileName');
return file.readAsString();
}
Uint8List stringToData(dataStr) {
List<int> list = dataStr.codeUnits;
return new Uint8List.fromList(list);
}
Future<File> createAudioFile(String fileName, Uint8List bytes) async {
String path = await docPath;
File file = new File('$path/$fileName');
return await file.writeAsBytes(bytes);
}
//here you can see how to use them
Future<File> testFile() async {
String dataStr = await dataToString();
File savedFile = await saveMediaAsString('codedFile', dataStr);
String contentSavedFile = await readFromStringMediaFile('codedFile');
Uint8List bytes = stringToData(contentSavedFile);
return await createAudioFile('test.mp3', bytes);
}
}

Cannot create a file in flutter

I have tried this code below but an empty folder i have found and still cannot create a file, but no errors found in the terminal.
here is the packages i have used :
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
this is the codes to create the file, is there something wrong:
Future<String> getFilePath() async {
Directory? appExtDirectory = await getExternalStorageDirectory();
String appExtPath = appExtDirectory.toString();
print('$appExtPath');
return appExtPath;
}
Future<File> get _localFile async {
final path = await getFilePath();
return File('$path/counter.txt');
}
Future<File> writeCounter() async {
final file = await _localFile;
// Write the file
return file.writeAsString("This is my demo text that will be saved to : counter.txt");
}
void saveFile() {
writeCounter();
}
Regards..
Try String appExtPath = appExtDirectory.path;

How to print a PDF file in Flutter

Here is my code
Future<File> _downloadFile(String url, String filename) async {
http.Client _client = new http.Client();
var req = await _client.get(Uri.parse(url));
var bytes = req.bodyBytes;
// String dir = (await getApplicationDocumentsDirectory()).path;
String dir = await ExtStorage.getExternalStoragePublicDirectory(
ExtStorage.DIRECTORY_DOWNLOADS);
File file = new File('$dir/$filename');
await file.writeAsBytes(bytes);
return file;
}
/// Prints a sample pdf printer
void printPdfFile() async {
var file = await _downloadFile(
"http://www.africau.edu/images/default/sample.pdf", "test.pdf");
await FlutterPdfPrinter.printFile(file.path);
}
I am implementing print PDF files which is saved in my device. When trying to print the document I am getting error like "A problem occurred configuring project ':flutter_pdf_printer'."
I am using flutter_pdf_printer dependency to print PDF files.
Convert your string url to URI, please make sure you are adding http
http: ^0.13.4
import 'package:http/http.dart' as http;
Uri uri = Uri.parse('Your link here');
http.Response response = await http.get(uri);
var pdfData = response.bodyBytes;
await Printing.layoutPdf(onLayout: (PdfPageFormat
format) async => pdfData);

Flutter - Network Image to File

I have an Image URL like "https://example.com/xyz.jpg". Now I want to put the image in a File type variable;
Something along these lines:
File f = File("https://example.com/xyz.jpg");
The whole point is to get the image from the given URL and save it as a File variable. How can I do so?
I searched for many solutions on the internet but there was no straightforward way to do so.
PS: I could have missed something where the question was similarly answered so please let me know the link where I can find it.
Edit: I am using the File type variable to pass it in the share function.
This is the library that I am using.
Here is my current on share button click code
if (file != null) {
ShareExtend.share(file.path, "image",
sharePanelTitle: "share image title",
subject: "share image subject");
}
Thanks for your help.
You need to download image and create an empty file then fill the file with image data:
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
Future<File> _fileFromImageUrl() async {
final response = await http.get(Uri.parse('https://example.com/xyz.jpg)');
final documentDirectory = await getApplicationDocumentsDirectory();
final file = File(join(documentDirectory.path, 'imagetest.png'));
file.writeAsBytesSync(response.bodyBytes);
return file;
}
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
Future<File> getImage({required String url}) async {
/// Get Image from server
final Response res = await Dio().get<List<int>>(
url,
options: Options(
responseType: ResponseType.bytes,
),
);
/// Get App local storage
final Directory appDir = await getApplicationDocumentsDirectory();
/// Generate Image Name
final String imageName = url.split('/').last;
/// Create Empty File in app dir & fill with new image
final File file = File(join(appDir.path, imageName));
file.writeAsBytesSync(res.data as List<int>);
return file;
}
Future<File> fileFromImageUrl() async {
String img='https://pps.whatsapp.net/v/t61.24694-24/160266256_1115367465775510_3546030680878251116_n.jpg?ccb=11-4&oh=01_AdSsrMGOPfs8CUJsEkYImMUu5L4DAzt2ym8eBrdsMG5O0Q&oe=63D7B45E';
final response = await http.get(Uri.parse(img));
final documentDirectory = await getApplicationDocumentsDirectory();
final file =
File(p.join(documentDirectory.path, 'File Name.jpg'));
file.writeAsBytesSync(response.bodyBytes);
return file;
}