2

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.

enter image description here

How can I add a local image instead? I tried adding the file path as shown below, but it did not work:

enter image description here

marcorivera8
  • 217
  • 1
  • 5
  • 13

2 Answers2

3

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');
Sajad Abdollahi
  • 1,593
  • 1
  • 7
  • 19
1

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

Sunil Chaudhary
  • 1,221
  • 12
  • 25