Today’s blog explores integrating Odoo with Flutter. Odoo is an efficient ERP system, and pairing it with Flutter mobile applications enables businesses to access and manage Odoo data on mobile devices. Here, we’ll focus exclusively on Flutter integration to demonstrate its usefulness for business operations.
Flutter, developed by Google for building natively compiled applications for mobile, web, and desktop from one codebase, offers an abundance of pre-designed widgets with fast development cycles to facilitate visually attractive yet highly engaging applications.
How to Set api calls in flutter
To enable API calls within your Flutter app, it’s necessary to add specific dependencies into the pubspec.yaml file. Here’s an outline of this process:
Open pubspec.yaml: This file, found at the root directory of your Flutter project, serves to manage dependencies within your app and will manage its dependencies efficiently.
Android Studio not showing flutter project's error- solution
Authenticating users with Odoo
To create an API service class in your Flutter application, you’ll want to follow these steps:
Step 1: Create the File
Create the File: In your Flutter project, navigate to the lib directory (or any appropriate folder for services) and create a new file named odoo_api_service.dart.
Step 2: Define the Class
Define the Class: Open the odoo_api_service.dart file and define a class that will manage your API calls. This class will contain methods for various API operations like fetching data, posting data, etc.
final String baseUrl = "http://your-odoo-instance.com/jsonrpc";
final String dbName = "your_db_name";
Future authenticate(String email, String password) async {
final Map payload = {
"jsonrpc": "2.0",
"method": "call",
"params": {
"db": dbName,
"login": email,
"password": password
}
};
final response = await http.post(
Uri.parse(baseUrl),
headers: {"Content-Type": "application/json"},
body: jsonEncode(payload),
);
if (response.statusCode == 200) {
final Map data = jsonDecode(response.body);
return data["result"]; // Returns user ID if login is successful
} else {
return null;
}
}
- Now, let’s build a login screen that authenticates users with Odoo. Create a new screen login_screen.dart and add the following code
import 'package:blog_app/api_call/api_services.dart';
import 'package:flutter/material.dart';
class LoginScreen extends StatefulWidget {
@override
_LoginScreenState createState() => _LoginScreenState();
}
class _LoginScreenState extends State {
final TextEditingController emailController = TextEditingController();
final TextEditingController passwordController = TextEditingController();
final OdooApiService apiService = OdooApiService();
void login() async {
int? userId = await apiService.authenticate(
emailController.text,
passwordController.text,
);
if (userId != null) {
print("Login successful! User ID: $userId");
// Navigate to Home Screen
} else {
print("Login failed. Please check credentials.");
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Odoo Login")),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
controller: emailController,
decoration: InputDecoration(labelText: "Email"),
),
TextField(
controller: passwordController,
decoration: InputDecoration(labelText: "Password"),
obscureText: true,
),
SizedBox(height: 20),
ElevatedButton(
onPressed: login,
child: Text("Login"),
),
],
),
),
);
}
}
Performing CRUD operations (Create, Read, Update, Delete)
CRUD operations are essential in any application for managing data efficiently. When integrated with an API, these operations allow users to create, read, update and delete resources. Below is a detailed explanation of each CRUD operation as well as instructions on how to implement them with Flutter API service classes.
Performing CRUD Operations in Flutter Create a New Record in Odoo
a) Adding a new customer to Odoo.
The Create operation allows you to add new records to the database. In a Flutter app, this is typically done using a POST request.
Future createCustomer(String name) async {
final response = await http.post(
Uri.parse(baseUrl),
headers: {"Content-Type": "application/json"},
body: jsonEncode({
"jsonrpc": "2.0",
"method": "call",
"params": {
"model": "res.partner",
"method": "create",
"args": [
{"name": name}
],
"kwargs": {},
"context": {}
}
}),
);
if (response.statusCode == 200) {
print("Customer created successfully!");
} else {
print("Failed to create customer.");
}
}
b)Read Data from Odoo
The Read operation retrieves data from the database. This can involve fetching a list of records or a specific record by its ID.
Future fetchCustomers() async {
final response = await http.post(
Uri.parse(baseUrl),
headers: {"Content-Type": "application/json"},
body: jsonEncode({
"jsonrpc": "2.0",
"method": "call",
"params": {
"model": "res.partner",
"method": "search_read",
"args": [],
"kwargs": {"fields": ["id", "name"]}
}
}),
);
if (response.statusCode == 200) {
print("Customers: ${response.body}");
}
}
c) Update an Existing Record
The Update operation modifies existing records in the database. This is usually done using a PUT or PATCH request, depending on whether you want to replace the entire resource or just update specific fields.
Future updateCustomer(int customerId, String newName) async {
final response = await http.post(
Uri.parse(baseUrl),
headers: {"Content-Type": "application/json"},
body: jsonEncode({
"jsonrpc": "2.0",
"method": "call",
"params": {
"model": "res.partner",
"method": "write",
"args": [[customerId], {"name": newName}],
"kwargs": {}
}
}),
);
if (response.statusCode == 200) {
print("Customer updated successfully!");
} else {
print("Failed to update customer.");
}
}
d) Delete a Record
The Delete operation removes records from the database. This is accomplished using a DELETE request.
Future deleteCustomer(int customerId) async {
final response = await http.post(
Uri.parse(baseUrl),
headers: {"Content-Type": "application/json"},
body: jsonEncode({
"jsonrpc": "2.0",
"method": "call",
"params": {
"model": "res.partner",
"method": "unlink",
"args": [[customerId]],
"kwargs": {}
}
}),
);
if (response.statusCode == 200) {
print("Customer deleted successfully!");
} else {
print("Failed to delete customer.");
}
}
Handling Errors and Best Practices
When working with API calls in your Flutter application, effective error handling and following best practices are crucial for creating a robust and user-friendly experience. Here’s how to approach error management and some essential guidelines to follow.
try {
final response = await http.post(Uri.parse(baseUrl));
if (response.statusCode == 200) {
print("Success!");
} else {
throw Exception("Failed to fetch data");
}
} catch (error) {
print("Error: $error");
}
Successfully Integrating Flutter with Odoo Using JSON-RPC APIs
Integrating Flutter with Odoo using JSON-RPC APIs is an effective way to enhance your applications. In this guide, we covered key steps like setting up API calls, authenticating users, performing CRUD operations, and handling errors. By following these steps you can ensure smooth interactions between Flutter app and Odoo, providing reliable user experiences while efficiently managing data management – the skills that enable you to build strong applications utilizing both Flutter and Odoo to their fullest extent.



