How to run Python scripts on Flutter

Original article was published by Hassan Javaid on Artificial Intelligence on Medium


Flutter and Python, using Flask

Introduction

There are many things being done in python that can’t be done in any other language, on top of which is Machine Learning, Data Mining, etc.

Python has some really helpful libraries like numpy and scikitlearn which makes machine learning and data science work easy for the programmers.

Code: https://github.com/ihassanjavaid/Iris-Predictor-Flutter-Flask

How-to

Hence, any easy way to run python scripts on flutter application is by making an API, and calling it from within the flutter project through the http package.

Step-1:

Import http package from here:

place that into your pubspec.yaml file and run `pub get`

flutter pub get

Step-2:

In your flutter project create a new file, let’s say I name it request.dart

Enter the following lines in that file

import 'package:http/http.dart';Future getData(url) async {Response response = await get(url);return response.body;}

Step-3:

Now, your flutter project is ready.

Go to PyCharm IDE, and create a new Flask Project.

How to create a flask project

Step-4:

By default, you would have this code in your app.py file

from flask import Flask

app = Flask(__name__)


@app.route('/')
def hello_world():
return 'Hello World!'


if __name__ == '__main__':
app.run()

You can rename the hello_world() function and implement whatever logic you want and return a string, number or an array.

When you would run your project, it will run on localhost.

Now for getting the output in flutter, instead of simply returning string, we need to return a json.

For that,

from flask import Flask, jsonify

app = Flask(__name__)


@app.route('/')
def hello_world():
json_file = {}
json_file['query'] = 'hello_world'
return jsonify(json_file)


if __name__ == '__main__':
app.run()

Now, instead of returning a string it is returning a json file like this

{
"query": "hello_world"
}

Step-5:

Now in your main flutter file, where you want to access, add this code in the function you want to get your output by python script.

var data = await getData('http://10.0.2.2:5000/);var decodedData = jsonDecode(data);print(decodedData['query']);

There you go, you have your output stored in decodedData.

Conclusion

This is how python scripts and .ipynb files can be executed using flutter. Code is available on my github page.

Covering in the next article:

  1. How to give input to python sciprt using http post method

That’s all for today!