Handling Flutter Strings like a Pro

Maruf Hassan
3 min readMay 8, 2021

--

After working on multiple projects, I have come to the conclusion that Part #7 Handling Flutter Internationalization like a Pro is a better approach to handling Strings compared to this article. I would advice to skip this article since this isn’t future-proof.

This is Part #2 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 String literals in a single dart file. This makes debugging so much easier and faster.

This is how people normally use Text widgets and Strings in general.

Disadvantages of using this way -

  1. IDE cannot detect String literals so any mistake goes unchecked.
  2. Debugging becomes a nightmare while you have to scavenge through different files to find the String.
  3. Bugfixes require multiple commits in different files becoming more prone to merge conflicts.

To fix this we create a class that holds all the Strings that our app will contain.

Create a dart file called strings.dart in constants folder.

The file will contain a class with a private constructor and Strings used in our app.

class Strings {  
Strings._();
static const String correctWay = "This is the way";
}

Strings are the class name.

Strings._(); 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.

correctWay is the String variable name.

“This is the way” is the value of the String.

Now that we understand what everything is, we will now use it.

Replace the floating String with Strings.correctWay.

Advantages of using this way -

  1. Any error is caught by the IDE and is easy to fix.
  2. Debugging becomes a breeze since all the Strings are in one file and fixing any spelling mistakes or changing any String variable is very easy.
  3. Bugfixes require a single commit as all the Strings are available in a single file, thus reducing the chances of merge conflicts.

I hope you liked the article. I plan to bring more short articles like these to teach tips and tricks used in Production Level Flutter Development!

You can read about Handling Flutter imports like a Pro in Part #1 of the series.

You can follow me on Twitter, Github, or Youtube to stay updated with all my new articles and videos.

--

--

Responses (1)