Handling Flutter Images like a Pro
This is Part #3 of the series in Flutter Production Level Development where I teach you all the tips and tricks used in an Industry Level Production app.
If you prefer videos over articles then you can watch the companion 1 min #Short video on this article.
When building a production-ready app, it is a good practice to keep all the Image assets in a single dart file. This makes debugging a lot easier and faster.
This is how people normally use Image widgets and Asset location in general.
Disadvantages of using this way -
- IDE cannot detect String literals so any mistake goes unchecked.
- Debugging becomes difficult while you have to scavenge through different files to find the Asset location.
- Bugfixes require multiple commits in different files becoming more prone to merge conflicts.
To fix this we create a class that holds all the Images that our app will contain.
Create a dart file called images.dart in the constants folder.
The file will contain a class with a private constructor and Images used in our app.
class Images {
Images._(); static const String logoLight = 'assets/images/logo/light_mode_logo.png';
}
Images is the class name.
Images._(); is a private constructor which prevents the class from being instantiated.
static means a member is available on the class itself instead of on instances of the class.
const makes the variable immutable.
logoLight is the Image asset name.
‘assets/images/logo/light_mode_logo.png’ is the asset location.
Now that we understand what everything does, we will apply it to our code.
Replace the floating Asset location with Images.logoLight
Advantages of using this way -
- Any error is caught by the IDE and is easy to fix.
- Debugging becomes a breeze since all the Images are in one file and fixing any spelling mistakes or changing any Image variable is very easy.
- Bugfixes require a single commit as all the Images are available in a single file, thus reducing the chances of merge conflicts.
I hope you liked the article. I plan on bringing more short articles like these to teach tips and tricks used in Production Level Flutter Development!
You can read about Handling Flutter Strings like a Pro in Part #2 of the series.
You can follow me on Twitter, Github, or Youtube to stay updated with all my new articles and videos.