Flask backend for a Flutter app in 3 steps
How to use a Flask backend in a Flutter app

Table of Contents
This is a draft for a Tutorial on how to use Flask as a backend in a Flutter app.
Step 1: Set up your Flutter project
- Create a new Flutter project using the Flutter CLI or your preferred IDE.
- Open the project in your chosen IDE.
Step 2: Create the Flask backend
- Install Flask by running the following command in your terminal:
pip install flask
- Create a new Python file, e.g.,
app.py
, and open it in a text editor or your preferred IDE. - Import the Flask module and create a Flask app instance:
from flask import Flask app = Flask(__name__)
- Define routes and their corresponding functions. These functions will handle the requests made by your Flutter app. For example:You can define more routes and functions as per your application’s needs.
@app.route('/api/data', methods=['GET']) def get_data(): # Code to fetch data from a database or any other data source data = {'message': 'Hello from Flask!'} return data
- Start the Flask development server by adding the following lines at the end of your
app.py
file:This will start the Flask server onif __name__ == '__main__': app.run()
http://localhost:5000
.
Step 3: Connect the Flutter app to the Flask backend
- In your Flutter project, open the
pubspec.yaml
file and add thehttp
package to your dependencies:Save the file, and rundependencies: http: ^0.13.4
flutter pub get
in your terminal to download the package. - Create a new Dart file, e.g.,
api_service.dart
, to handle HTTP requests to the Flask backend. - Import the necessary packages:
import 'package:http/http.dart' as http; import 'dart:convert';
- Create a class to handle API requests:Adjust the
class ApiService { static const String baseUrl = 'http://localhost:5000'; Future<dynamic> getData() async { final response = await http.get(Uri.parse('$baseUrl/api/data')); if (response.statusCode == 200) { return jsonDecode(response.body); } else { throw Exception('Failed to fetch data from the backend.'); } } }
baseUrl
to match the URL where your Flask server is running. - In your Flutter app code, import the
api_service.dart
file and call the API to retrieve data:Make sure to replacevoid fetchData() { ApiService().getData().then((data) { // Process the retrieved data print(data); }).catchError((error) { // Handle error print(error); }); }
fetchData()
with an appropriate method in your Flutter app code. - Run your Flutter app and make the API call. You should see the data printed in the console.
That’s it! You have now set up Flask as the backend for your Flutter app and established communication between the two. I’m gonna expand upon this tutorial to add more routes, handle different types of requests, and incorporate additional functionality in a follow-up post.