Testing Localized Widget in Flutter

Hyo
CodeChai
Published in
2 min readFeb 24, 2019

I’ve been fighting with the issue I’ve posted in the flutter repository for a while and finally, I’ve found the workaround with the support of the finding @remonh87 has provided🎉.

When you try to integrate internationalization in your flutter app following the official guide, you will end up your localization.dart file with something like below.

Note that my JSON files are located in `res/langs/en.json`and `res/langs/ko.json`.

Then your main.dart will look like below.

Then you will be able to use the localization in your widget by calling Localization.of(context).trans(<YOUR STRING>).

`localization.trans(‘LOADING’)` is where we use localized functionality.

Now it’s time for us to test the widget. Therefore I’ve written below in test/widget.dart.

Note that ‘Loading’ text is the result of `Localization.of(context).trans(‘LOADING’)`.

Time to run flutter test and guess what?

Yeah, it’s the error!

I’ve had a considerable amount of time trying to resolve this problem and ended up posting issue in flutter repo. Today, I’ve found the actual problem. The flutter test can’t actually load json from a file and grab the strings out there. Also, your widget won’t load correctly if you try to load them from a file. Whenever I’ve found out the actual problem, I thought I could finally make a workaround and go for restructuring my localization a bit.

Note that there is `isTest` param passed down. I am trying to test only the key value here since `json` file couldn’t be loaded.

As you can see in the above code, I’ve added test env with the isTest parameter in Localization class. If the isTest parameter is set to true, it will call theloadTest method instead load. So let’s update the test code.

Note that I’ve passed the `isTest` value to true. Also, changed `find.text(‘LOADING’)` instead ‘Loading’ because I am only testing the key value for now since the JSON file couldn't be loaded.

Now it is time to run flutter test again and see if we’ve made it.

Yes, we’ve made it now 🎉. However, I don’t know if this is sufficient for others because it is only testing the key value.

I know this is an easy solution after finding out exactly what’s going wrong. I’ve just posted this for people who will be suffering like me having a considerable amount of time headbanging.

Hope you like it!

The Flutter Pub is a medium publication to bring you the latest and amazing resources such as articles, videos, codes, podcasts etc. about this great technology to teach you how to build beautiful apps with it. You can find us on Facebook, Twitter, and Medium or learn more about us here. We’d love to connect! And if you are a writer interested in writing for us, then you can do so through these guidelines.

--

--