How To Link Python Script (.py file) With Flutter App


Step-1 : Configuring Flask Project

First of all Create a Flask Project in Pycharm IDE (You can use any IDE of your choice)

once your project is created you will see something like

from flask import Flask

app = Flask(__name__)


@app.route('/')

def hello_world():

return 'Hello World!'


if __name__ == '__main__':

app.run()

Try Running this python file (app.py)

Output will generate a server link try running it on Your Browser . You will see link somethink like:

http://127.0.0.1:5000/

now lets make some tweaks in our app

replace

@app.route('/')

with

@app.route('/api')


Now we run the code .......

We see our root url become

127.0.0.1:5000/api

And without api in root url webpage is not loaded


step 2: To pass Query as input

Now let's change our base code to make webpage display Query passed to it .......

from flask import Flask,request


app = Flask(__name__)



@app.route('/api',methods=['GET'])

def hello_world():

Query = request.args[]


if __name__ == '__main__':

app.run()

in line 8 we are declaring variable Query to take input from user for that we have to import request module from flask in line 1.

After that we used syntax Query = request.args to pass argument in Query Variable and also 'GET' method in parameters in line 8. for which


Now we can pass any data into api using GET method. So for that pass 'Query' in args[] and convert it into string using :

Query = str(request.args['Query'])

return Query


Now rerun your Code to see the following changes in browser

now pass the Query value you want to assign to Query as output on your screen

after the api? in url box such as: 127.0.0.1:5000/api?Query=Hi There I am Vaibhav A tech And Travel Blogger

so as you can see following output is shown which we entered in query .

step 3 : Convert it in Json format

now as we know this returns just a simple text on screen but this text is of no use in flutter base . So we need to return Query as a json format.


So we can do it very simply just remove the return Query and declare an empty dictionary and then store the query value in the dictionary and after that import jsonify and after that return jsonify and pass your declared dictionary as parameter in it.

from flask import Flask,request,jsonify


app = Flask(__name__)



@app.route('/api',methods=['GET'])

def hello_world():

d = {}

d['Query'] = str(request.args['Query'])

return jsonify(d)


if __name__ == '__main__':

app.run()

Now try Rerun your code

Now we can get json format of our query.

This is just a basic code we can write any of python code using flask and make it a web app on server.

So, its upto you how you want to replace them with brand new script but always remember to return JSON format to run it on flutter base.

step 4 : To link our Api Which we built in flask to Flutter

so firstly we will create a simple app UI using flutter .

for that we will follow these simple step

step-1 :open code directory folder in VS code

step-2 :open terminal

step-3 :run command "flutter create App-Name"

step-4 :create simple App UI using following syntax in main.dart

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

home: Scaffold (

appBar: AppBar(

title: Text('PYTHON AND FLUTTER'),

), // AppBar

body: Column (

children: <Widget>[

TextField(),

Text('QUERY'),

], // <Widget>[]

), // Column

), // Scaffold

), // MaterialApp

}


Widget build(BuildContext context) {

return MaterialApp(

home: Scaffold (

appBar: AppBar(

title: Text('PYTHON AND FLUTTER'),

), // AppBar

body: Column (

children: <Widget>[

Padding(

Padding: const EdgeInsets.all(10.0),

child: TextField(),

), // Padding

Padding(

Padding: const EdgeInsets.all(10.0),

child: Text(

'QUERY',

style: TextStyle(fontSize: 30.0, fontWeight: FontWeight.bold),

),//Text

), // Padding

], // <Widget>[]

), // Column

), // Scaffold

), // MaterialApp

}

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

String url;

var Data;

@override

Widget build(BuildContext context) {

return MaterialApp(

home: Scaffold (

appBar: AppBar(

title: Text('PYTHON AND FLUTTER'),

), //AppBar

body: Column (

children: <Widget>[

Padding(

Padding: const EdgeInsets.all(10.0),

child: TextField(

decoration: InputDecoration(

hintText: 'Search Anything Here'

)

), // TextField

), //Padding

Padding(

Padding: const EdgeInsets.all(10.0),

child: Text(

'QUERY',

style: TextStyle(fontSize: 30.0, fontWeight: FontWeight.bold),

),//Text

), // Padding

], // <Widget>[]

), // Column

), // Scaffold

), // MaterialApp

}





Now add http: in pubsec.yaml

without mentioning version number .......

Now create a dart file api.dart in lib folder. And write following Code


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


Future Getdata(url) async {

http.Response Response = await http.get(url);

return Response.body;

}


Now go back to main.dart .

import 'API.dart';

Now we call flask url that we created in previous part and Now we try take input from user using this syntax for that come back to

child: TextField{

onChanged: ( ) { }

}

to

onChanged: (value) {

url = 'http://10.0.2.2:5000/api?Query=' + value.toString();

},

Now comes the main part to work. Now whenever user types in text filed that query should get added in fronted of generated url

Padding(

Padding: const EdgeInsets.all(10.0),

child: TextField(

onChanged: (value) {

url = 'http://10.0.2.2:5000/api?Query=' + value.toString();

},

decoration: InputDecoration(

hintText: 'Search Anything Here',

suffixIcons: GestureDetector(onTop: ()async{

Data = await Getdata(url);

var DecodedData =

},child: Icon(Icons.search))

),// InputDecoration

), // TextField

), //Padding

Now import dart.convert in main.dart file . So, that we can decode JSON data .....

import 'package:flutter/material.dart';

import 'API.dart';

import 'dart:convert';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {

@override

_MyAppState createState() => _MyAppState();

class _MyAppState extends State<MyApp> {

String url;

var Data;

String QueryText='QUERY'; // Added QueryText to save String value decoded

@override

Widget build(BuildContext context) {

return MaterialApp(

home: Scaffold (

appBar: AppBar(

title: Text('PYTHON AND FLUTTER'),

), //AppBar

body: Column (

children: <Widget>[

Padding(

Padding: const EdgeInsets.all(10.0),

child: TextField(

onChanged: (value) {

url = 'http://10.0.2.2:5000/api?Query=' + value.toString();

},

decoration: InputDecoration(

hintText: 'Search Anything Here',

suffixIcons: GestureDetector(onTop: ()async{

Data = await Getdata(url);

var DecodedData = jsonDecode(Data);

setState(() {

QueryText = DecodedData['Query'];

});

},

child: Icon(Icons.search))

),// InputDecoration

), // TextField

), //Padding

Padding(

Padding: const EdgeInsets.all(10.0),

child: Text(

QueryText,

style: TextStyle(fontSize: 30.0, fontWeight: FontWeight.bold),

),//Text

), // Padding

], // <Widget>[]

), // Column

), // Scaffold

), // MaterialApp

}


Now Run the above code .....As you can its working properly
In the Next part we will try to built some amazing app using python Flask Untill then stay tuned .......
For this Project refrence checkout this github repo : https://github.com/cyclone-pk/pythonandflutter