Python + Flutter part 2

Jakes
4 min readFeb 22, 2020

--

Now this is the second article which i will be writing of a practical way of how to connect the python rest api to flutter.

So we going to start by writing some few lines in python.Before continuing with all this make sure you have followed the steps as follows in the previous part 1 that i wrote its very important.

The good thing with flak we don’t need lots of file like django so follow the steps below:

  1. Create a project folder then open the project folder in Atom Editor.
  2. Create new file called app.py
  3. We going by starting writing a very simple flask code in python for only getting the stores which are just stored as dictionary in python.
from flask import Flask, jsonify,request

app = Flask(__name__)
stores = [
{
'name' :'Shoes Store',
'ratings':'8.4',
'image':'https://cdn.pixabay.com/photo/2016/04/12/14/08/shoe-1324431_960_720.jpg',
'items':[
{
'item_name' :'Nike 510',
'item_image':'https://cdn.pixabay.com/photo/2015/05/31/10/54/shoes-791044_960_720.jpg',
'item_price':'$500.0',
}
]
},
{
'name' :'Soko',
'ratings':'8.4',
'image':'https://cdn.pixabay.com/photo/2017/06/17/09/47/shopping-2411667_960_720.jpg',
'items':[
{
'item_name' :'Nike 510',
'item_image':'https://cdn.pixabay.com/photo/2015/05/31/10/54/shoes-791044_960_720.jpg',
'item_price':'$500.0',
}
]
},
{
'name' :'Shoes Store',
'ratings':'8.4',
'image':'https://cdn.pixabay.com/photo/2014/05/03/01/02/concert-336695_960_720.jpg',
'items':[
{
'item_name' :'Nike 510',
'item_image':'https://cdn.pixabay.com/photo/2015/05/31/10/54/shoes-791044_960_720.jpg',
'item_price':'$500.0',
}
]
}
]

@app.route('/store')
def get_stores():
return jsonify({'stores': stores})

app.run(debug=True, host="ipV4Adress")



# 192.168.43.39
# accessing Ipv4
# ipconfig
  1. get all stores = http://ipv4Adress:5000/store

In the host where bolded you will need to get your ipV4 address for you pc or mac this makes your api available to all devices with an internet connection.You can try in your phone.

So to get the IpV4 in Windows go to your command prompt and write “ipconfig”.

After that we will have to run our flask app still in the command prompt.To run just write python app.py make sure you are in the project file directory.

If you are completely new in command prompt to navigate to your folder just write cd “folder name”.Ok If you have done all this then you should get something like this i in you command prompt.

And thats all for the Python backend.If you enter the address in the broswer it will show something like this.

Lets go now to the flutter side which is pretty easy and so it wont be that hard so we are going to display the data in the right way no short cuts convert the json data in dart and use future builder to load the data.

Store_Model.dart

import 'package:flutter/cupertino.dart';
import 'package:http/http.dart';




class Stores{
final String name;
final String ratings;
final String image;
final List<Items> items;

Stores({@required this.name,@required this.ratings,@required this.image,this.items, });

factory Stores.fromJson(Map<String, dynamic> json) {
return Stores(
name: json['name'] as String,
ratings: json['ratings'] as String,
image: json['image'] as String,
items: List.from(json['items']).map((items) => Items.fromJson(items)).toList()
);
}

Map toStores() {
var map = Map<String, dynamic>();
map['name'] = name;
map['ratings'] = ratings;
map['image'] = image;
map['items'] = [];
return map;
}
}

class Items {
final String item_name;
final String item_image;
final String item_price;

Items({@required this.item_name,@required this.item_image,@required this.item_price,});

factory Items.fromJson(Map<String, dynamic> json){
return Items(
item_name: json['item_name'],
item_image: json['item_image'],
item_price: json['item_price']
);
}
}
String url = "http://ipV4Adress:5000/store";
Future<List<Stores>> fetchStores(http.Client client) async {
final response = await client.get(url);
return compute(parseStores,response.body);
}
List<Stores> parseStores(String responsebody) {
final parsed = json.decode(responsebody);
return (parsed["stores"] as List)
.map<Stores>((json) => new Stores.fromJson(json))
.toList();
}

Home.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_py/add_image.dart';
import 'package:flutter_py/api_testing.dart';
import 'package:flutter_py/show.dart';

import 'models.py.dart';
import 'package:http/http.dart' as http;
class Home extends StatefulWidget {
Home({Key key}) : super(key: key);

@override
_HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

@override
void initState() {
// TODO: implement initState
super.initState();
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(statusBarColor: Colors.transparent));
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
elevation: 0.0,
title: Text('Stores',style: TextStyle(color: Colors.black,fontSize: 30),),
),
body: FutureBuilder<List<Stores>>(
future :fetchStores(http.Client()),
builder: (context,snapshot){
print(snapshot.data);
if (snapshot.hasData) {
print(snapshot.data);
return PhotosList(photos: snapshot.data);
} else if (snapshot.hasError) {
Center(
child :Text(snapshot.error)
);
}
return CircularProgressIndicator();
}),
floatingActionButton: FloatingActionButton(
child: Center(child: Icon(Icons.add, color: Colors.white,),),
onPressed: ()=>Navigator.of(context).push(MaterialPageRoute(builder: (context)=>AddImage()))
),
);
}
}


class PhotosList extends StatelessWidget {
final List<Stores> photos;

PhotosList({Key key, this.photos}) : super(key: key);

@override
Widget build(BuildContext context) {
return GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemCount: photos.length,
itemBuilder: (context, index) {
return Padding(padding: EdgeInsets.all(5),
child: GestureDetector(
onTap: ()=>Navigator.of(context).push(MaterialPageRoute(builder: (context)=>Show(stores: photos[index],),)),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20)),
image: DecorationImage(image: NetworkImage(photos[index].image,),fit: BoxFit.cover)
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded(child: SizedBox()),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(photos[index].name,style: TextStyle(fontSize: 20,color: Colors.white,fontWeight: FontWeight.w600),),
)
],
)
),));
}
);
}
}

The final Results in Flutter

Github source code : https://github.com/JohnKinyanjui/flutter_with_python

--

--

Jakes

Developing apps and more stuff is a passion.I develop when listening music because programming is like writing a hit song.Will you write yours?