how to get XFile populated with images from flutter project assets?

Viewed 18

how to get XFile populated with images from flutter project assets? how to get XFile populated with images from flutter project assets?

1 Answers

You can use rootBundle from the services.dart package. Import the package like this:

import 'package:flutter/services.dart' show rootBundle;

And call the following function to get the image from asset and populate XFile:

Future<XFile> getImageFileFromAssets() async {
    final byteData = await rootBundle.load('./assets/image.png');

    final file = File('${(await getTemporaryDirectory()).path}/image.png');
    await file.writeAsBytes(byteData.buffer
        .asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));

    XFile xFile = XFile(file.path);

    return xFile;
  }
Related