Flutter with Flask ! Performing Machine learning operation using Flask in Flutter

Devbillion
3 min readApr 15, 2021

--

Performing supervised ML algorithms in Flutter is easy when we use Flask framework. I recently tried this approach for my final year project where I need to perform Machine learning algorithm in flutter. I came across many methods but using flask made more easier than other for flutter.

Here we are going to write an algorithm for Multiple Linear Regression.

Step 1 — Create a flask project in Pycharm.

Flask Project Creation — flutter with flask

Step 2 — Write an Algorithm What you need in app.py file.

import pandas as pd
import matplotlib.pyplot as plt
from flask import Flask, flash, request, redirect, url_for, render_template


app = Flask(__name__)


@app.route('/')
def hello_world():
Stock_Market = {
'Year': [2017, 2017, 2017, 2017, 2017, 2017, 2017, 2017, 2017, 2017, 2017, 2017, 2016, 2016, 2016, 2016, 2016,
2016, 2016, 2016, 2016, 2016, 2016, 2016],
'Month': [12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
'Interest_Rate': [2.75, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.25, 2.25, 2.25, 2, 2, 2, 1.75, 1.75, 1.75, 1.75, 1.75,
1.75, 1.75, 1.75, 1.75, 1.75, 1.75],
'Unemployment_Rate': [5.3, 5.3, 5.3, 5.3, 5.4, 5.6, 5.5, 5.5, 5.5, 5.6, 5.7, 5.9, 6, 5.9, 5.8, 6.1, 6.2, 6.1,
6.1, 6.1, 5.9, 6.2, 6.2, 6.1],
'Stock_Index_Price': [1464, 1394, 1357, 1293, 1256, 1254, 1234, 1195, 1159, 1167, 1130, 1075, 1047, 965, 943,
958, 971, 949, 884, 866, 876, 822, 704, 719]
}

df = pd.DataFrame(Stock_Market,
columns=['Year', 'Month', 'Interest_Rate', 'Unemployment_Rate', 'Stock_Index_Price'])
fig = plt.figure()

plt.scatter(df['Interest_Rate'], df['Stock_Index_Price'], color='red')
plt.title('Stock Index Price Vs Interest Rate', fontsize=14)
plt.xlabel('Interest Rate', fontsize=14)
plt.ylabel('Stock Index Price', fontsize=14)
plt.grid(True)
fig.savefig('static/alg.png', dpi=50)
return 'localhost:5000/display/alg.png'

@app.route('/display/<filename>')
def display_image(filename):
return redirect(url_for('static', filename=filename), code=301)


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

In above code, We are performing the algorithm with the given data and we are converting the result to an image.

We are saving that image to the static folder of the flask project “fig.savefig(‘static/alg.png’, dpi=50)”.

Finally we are returning the image url.

Step 3 — creating Flutter project.

Create a new flutter project.

Step 4 — Importing HTTP package.

you can import this package from this link https://pub.dev/packages/http

import 'package:http/http.dart' as http;

Step 5 — Write a HTTP method that interacts with Flask

getData() async{
http.Response response = await http.get('localhost:5000');
return response.body;
}

Step 6 — Complete the Home page Design.

Under the main.dart file

class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
bool gotvalue = false;
var imageUrl;

getData() async{
http.Response response = await http.get('localhost:5000');
return response.body;
}


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Flutter with Flask"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Supervised Learning demo',
),
gotvalue?Container(
child:Image.network(
imageUrl)):
RaisedButton(onPressed:() async{
var data = await getData();
print(data);
setState(() {
imageUrl = data;
gotvalue = true;
});
},
child: Text("Predict"),
)
],
),
),
);
}
}

The layout will be

Home Page — flutter with flask

Step 7 — Run the flask project

Flask project — flutter with flask

Step 8 — press the predict button in flutter app

Flutter output — flutter with flask

These are the steps we used to link our flutter and flask project.

We can use this method to perform all kind of machine learning in Flutter using Flask.

--

--

Devbillion
Devbillion

Responses (1)