Combining python and flutter: Part 2

Mandar Bhide
3 min readJul 7, 2020

Hello there! Welcome back to the second part of ‘Combining python and flutter’. In the first part, we saw how we can get our own ‘countries.json’ file which contains countries with their calling codes. Now its time to use that file into a login page.

Let’s get started.

First of all, we need to move the ‘countries.json’ to assets folder then run ‘flutter pub get’. Back to our main.dart, we’ll use DefaultAssetBundle class to load our json file. It is recommended as it allows to change the asset bundles at runtime, which is useful for multiliguial assets. from loadString() method, we get all the contents of specified file as a string. To read the string as json file, we need dart:convert library, which allows conversion between common data representations like Json or Utf-8. In this function, we update another list of names of countries, just for convenience for the widget we’ll see afterwards.

In this function ‘json’ is instance of JsonCodec class of convert library, which allows to handle json file format. decode() method returns object/array of objects in the given json string. In this case, we get an array of objects. But we want the object to be a well structured country’s data. Thus we create a class Country and add a factory method fromJson() which takes a decoded json object as argument, assigns the corresponding values to a new Country object and returns it.

In the build function, we create a widget DropDownButton<String>. ‘value’ is the value to be displayed on dropdown when it is collapsed. For items, we map the ‘names’ array by the function. The argument to this function is name of each country from names array. Thus we find the country from its name in list array and store its index in variable x. For each item in names array, we return a DropdownMenuItem which displays name of country and its dialling code.

onChanged method of dropdown is invoked when we open dropdown and select an object from it. Its argument type depends upon the type of dropdown. Here it is String and takes name of country as argument. Here, we again find the country by its name in the ‘list’ array and update the index accordingly and update the value to be displayed on the collapsed dropdown.

Then we create a simple textfield for user to enter the phone number and a submit button. onPressed is invoked when the user clicks the button. Here we create getOTP method. In this method, we append ‘+’ and country code before the phone number entered by user. This number will be used in same method to request an OTP and verify it.

number = "+" + list[index].code + number;

And done! Your app is ready to go global in terms of authentication!

Hope you enjoyed the article. Give it a clap if you found it useful. Wish you happy fluttering!

--

--

Mandar Bhide

Computer Engineering student | Web and app developer| Love to learn technologies :)