Starting with Flutter: Asset usage on app

If your app needs some kind of graphics or file to work, your best option is to add assets to your application. With assets you can have images, audio, fonts and videos inside your flutter app. The great thing is that adding them is pretty easy and retrieving them is still a breeze!

Pubspec.yaml

Every asset must be nominated into the project pubspec.yaml file. Fortunately you don’t need to add every file singularly but you can write down only the folder in which there is. To add them you should write down this under the “flutter” section of the pubspec.yaml file.

flutter:
  assets:
    - myfolder/
    - myfolder/myGraphics
    - myfolder2/myGraphics2

The path always starts from the main folder of the project so you only need to add the relative one. 

 

Retrieving assets

Widgets should expose methods to use assets, like Image does (Image.asset("PATH")). The path to add is the absolute one starting from the project directory with the file name at the end with the extension. Considering the example above:

Image.asset('assets/myfolder/image.png')

Some tricks

  • Create a function which will get a file name and will return the full asset path with the file at the end.
  • Use the iOS typical folder structure, Flutter will retrieve automatically the correct asset.
    • Use the default folder for 1.0x then add 2.0x and 3.0x assets
  • You can add custom fonts to assets folder, files… It’s not only for audio and images. Remember always to add additional folders/files to the pubspec.yaml file.

Add a Comment

Your email address will not be published. Required fields are marked *