Combining python and flutter : Part 1

Mandar Bhide
2 min readJul 6, 2020

Hello everyone! Hope you are doing good.
Recently I tried building an app in flutter that required user authentication. I was using firebase for authentication with phone number and OTP.

On very first page of login, I faced an issue.
Its very simple if app is supposed to be used in only one country/region. You can just do:

But what if you want your app to go global? According to countrycode.org, there are 240 country/region codes. How to collect them all?

One way is to google for it and copy-paste the code from stackoverflow or github etc. But I wanted to be ‘Atma Nirbhar’(Self-reliant), so, next option!

The other way I thought of was using a .json file from web. Even I found one on github. But very first comment stating repetition of countries made me discard it and create my own .json file. Manually typing 240 countries/regions into a json file is indeed a foolish idea. So I thought why not to make my python skills work for me?

So I created a simple web scraper in python using BeautifulSoup. Let’s get started!

First we make an http request to countrycode.org. In response to our request, we get all the contents of page. Then we use BeautifulSoup to parse the contents as html markup and extract the required data from it.

Here we use function which takes a row from the extracted table and returns a string of corresponding data that can be inserted to a .json file.
(Warning: Do NOT forget the ‘\’ character before each double-quote, as missing any one of them will generate error in script.)

But there is a small error. As you can see, we insert a comma after every country’s data, which results into a comma after the last country. Also, to be a valid .json file, we must close the opened square-bracket. So we adjust final string as:

string = string[:-1]string += "]"

Now when all the contents of our ‘countries.json’ are ready, let’s go to code and open a file. Remember to open file in preferably ‘w’ mode. As default mode is ‘r’, we will face error for this as well as further lines of code. Then we simply write the previously created string to the file and close it as:

file = open("countries.json","w+")file.write(string)file.close

Running this whole script will generate ‘countries.json’ in the working directory.

Thanks a lot for reading. Integration of this .json file into flutter will be discussed in the next part for two reasons: first, short is sweet and secondly, typing and editing takes time. 😁

See you in next part!

--

--

Mandar Bhide

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