Flutter Connect With Django REST API

Flutter + Django + MySQL

Geno Tech
App Dev Community

--

Image: Flutter with Django REST API

Welcome to another Flutter knowledge-sharing story. As a Flutter developer, We all know that We should learn about fundamental usages which applying frequently in a mobile application. At that time we have so many solutions for backend REST API. Django is a python framework that we can see as a modern solution. PHP is a bit old but a common selection of developers. Also, I have done tutorials of those PHP API crud operations in Flutter. This is another step to create an API using Python and MySQL. I hope this will be really helpful for start. With this one, you can learn so much about what you do in the future. The next story will describe how to perform CRUD operations with Python and MySQL using the Django framework. I repeat that this is very useful for beginners. So, I will show every step and you just need to follow them and see the outputs.

Pre-requisites

  1. Install any apache + PHP + MySQL stack (XAMPP/ WAMP)
  2. Flutter installation. (Android Studio / VS Code)

Django Implementation

The first thing you need to get started, install Django and other libraries inside your PC by following steps.

pip install django
pip install djangorestframework

Then, you want to create a Django project. For that, inside the htdocs folder in Xammp, run the following command on cmd.

django-admin startproject crudexample

Inside the crudexample folder, run the following command and create the employee app.

python manage.py startapp employee

Then you can see the project that we created crudexample and inside that, the employee app. I will add the project structure at the end of this part.

So we should create the database name ‘django’. So we can create the connection and create the tables.

In the settings.py file, you need to create the following three changes. Without any difficulty, you can identify what are the changes and mean of them.

settings.py

// Change #1
ALLOWED_HOSTS = ['10.0.2.2', '127.0.0.1']
// Change #2
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'employee'
]
// Change #3
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'django',
'USER':'root',
'PASSWORD':'',
'HOST':'localhost',
'PORT':'3306'
}
}

Create a Model for employee table

models.py

# Create your models here.
class Employee(models.Model):
eid = models.CharField(max_length=20)
ename = models.CharField(max_length=100)
eemail = models.EmailField()
econtact = models.CharField(max_length=15)
class Meta:
db_table = "employee"

Then run the migration for creating the tables of the ‘django’ DB.

python manage.py makemigrations

So the tables should be created as follows.

Then add some data to the employee table and go ahead with the following steps.

Create the serializer.py

from rest_framework import serializers

from .models import Employee


class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = [
'ename',
'eemail'
]

view.py

from django.shortcuts import render, redirect
from employee.models import Employee
from .serializers import EmployeeSerializer
from rest_framework import viewsets


# Create your views here.
class Employee(viewsets.ModelViewSet):
queryset = Employee.objects.all()
serializer_class = EmployeeSerializer

Provide Routing

from django.contrib import admin
from django.urls import path, include
from employee import views
from rest_framework import routers

router = routers.DefaultRouter(trailing_slash=False)
router.register('employeedetails', views.Employee)

urlpatterns = [
path('', include(router.urls)),
]

So finally the project structure of the back end is like this,

Image: Back End Structure

Then you can check the output of the backend in your browser,

First, run the server using the following command and see the output.

C:\xampp\htdocs\crudexample>python manage.py runserver

If it successfully completed, you can see like following in the cmd,

C:\xampp\htdocs\crudexample>python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
September 05, 2021 - 20:23:21
Django version 3.2.7, using settings 'crudexample.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

Backend Output

URL: http://127.0.0.1:8000/employeedetails

Image: Django REST API output

Cool !!! Let us move to flutter implementation.

Flutter Implementation

As usual, create a flutter project first, then I am going to connect with the android application to the above back end.

First, allow the internet permissions inside the AndroidManifest.xml file.

<uses-permission android:name="android.permission.INTERNET"/>

Then, change the homepage as follows,

import 'package:flutter/material.dart';

import './screens/home.dart';

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

class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter + Django',
initialRoute: '/',
routes: {
'/': (context) => Home(),
},
);
}
}

Create the env.sample.dart file same in the level of the main.dart file. There you create the global variable to mention the base URL.

class Env {
static String URL_PREFIX = "http://10.0.2.2:8000";
}

Inside the model folder, Create the employee.dart model file for build employee objects.

class Employee {
final String eid;
final String eemail;
final String ename;


Employee({this.eid, this.eemail, this.ename});

factory Employee.fromJson(Map<String, dynamic> json) {
return Employee(
eid: json['eid'],
ename: json['ename'],
eemail: json['eemail'],
);
}

Map<String, dynamic> toJson() => {
'eid' : eid,
'ename': ename,
'eemail': eemail,
};
}

Then create the screens folder and inside it, initialize the home.dart file.

home.dart

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

import '../env.sample.dart';
import '../models/employee.dart';

class Home extends StatefulWidget {
@override
HomeState createState() => HomeState();
}

class HomeState extends State<Home> {
Future<List<Employee>> employees;
final employeeListKey = GlobalKey<HomeState>();

@override
void initState() {
super.initState();
employees = getEmployeeList();
}

Future<List<Employee>> getEmployeeList() async {
final response = await http.get("${Env.URL_PREFIX}/employeedetails");

final items = json.decode(response.body).cast<Map<String, dynamic>>();
List<Employee> employees = items.map<Employee>((json) {
return Employee.fromJson(json);
}).toList();

return employees;
}

@override
Widget build(BuildContext context) {
return Scaffold(
key: employeeListKey,
appBar: AppBar(
title: Text('Employee List'),
),
body: Center(
child: FutureBuilder<List<Employee>>(
future: employees,
builder: (BuildContext context, AsyncSnapshot snapshot) {
// By default, show a loading spinner.
if (!snapshot.hasData) return CircularProgressIndicator();
// Render employee lists
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
var data = snapshot.data[index];
return Card(
child: ListTile(
leading: Icon(Icons.person),
title: Text(
data.ename,
style: TextStyle(fontSize: 20),
),
),
);
},
);
},
),
),
);
}
}

In the end, You can see the final output that we need, as follows.

Image: Django + Flutter connected

Conclusion

This story gives you the knowledge of how to connect together flutter, Django(python), and MySQL. As part two, I will guide you on how to perform the CRUD operations using these technologies. Please feel free to ask any question you will face in the response section below.
Happy Coding !!!!
Found this post useful? Kindly tap the 👏 button below! :)

--

--

Geno Tech
App Dev Community

Software Development | Data Science | AI — We write rich & meaningful content on development, technology, digital transformation & life lessons.