How to Read Files From Assets Folder as ByteData/Uint8List or String in Flutter App
In this example, we are going to show you how to load files such as audio, video, documents, images field from Asset Folder as ByteData, Uint8List, or base64 in Flutter App. We have sown the way to read text files as String. See the example below:
Be sure, you have indexed asset folders and files in pubspec.yaml file.
flutter: # The following line ensures that the Material Icons font is # included with your application, so that you can use the icons in # the material Icons class. uses-material-design: true # To add assets to your application, add an assets section, like this: assets: - assets/audio/ - assets/textfiles/ # - images/a_dot_ham.jpeg
And place your files in the assets folder.
String textasset = "assets/textfiles/file.txt"; //path to text file asset String text = await rootBundle.loadString(textasset); print(text); //output: Text: Hello, this is FlutterCampus.com and you are learning Flutter.
import 'dart:typed_data'; import 'package:flutter/services.dart';
String audioasset = "assets/audio/ambulance_sound.mp3"; //path to asset ByteData bytes = await rootBundle.load(audioasset); //load sound from assets Uint8List soundbytes = bytes.buffer.asUint8List(bytes.offsetInBytes, bytes.lengthInBytes); //you can load image file too
You can load Image, PDF, DOCX, XLSX, and other file formats too from the Assets folder with this same code. You can convert this loaded file to any data type you want. Look at this reference to convert: How to Encode/Decode Path, File, Bytes, and Base64 in Dart/Flutter
String basestring = base64.encode(soundbytes); print(basestring); /* output: SUQzAwAAAAAfdlBSSVYAAAAOAABQZWFrVmFsdWUAm34AAFBSSVYAAAARAABBdmVyYWdlTGV2ZWwAExkA .... more long string */
In this way, you can load or read any kind of files from the Assets Folder in the Flutter App.
No any Comments on this Article