how-to-master-state-management-in-flutter-with-example

How to Master State Management in Flutter?

Mastering State Management in Flutter: Handling API Data Efficiently (With Odoo REST API)

Why are we using state management in Flutter? Imagine creating a large-scale Flutter app with many API calls, UI screens, and components. In a usual case, these situations would be very hard to handle, but if we use state management, we can easily handle this situation. 

There are different types of state management in Flutter. You can use these state management techniques according to the situation.

These are the best options for working with api: 

Getx: Lightweight, reactive state management

Provider: Simpler apps with minimal API calls

Riverpod: Scalable and flexible state handling

Bloc (Business Logic Component): Large-scale apps with complex API interactions

This blog will focus on GetX due to its simplicity, speed, and minimal boilerplate code. Let’s integrate GetX with the Odoo REST API for clean and efficient state management.

API-Driven Flutter App with GetX and Odoo

In this guide, we’ll cover:

  • Setting Up Your Flutter Project with your state management  
  • Connecting Flutter to Odoo REST API
  • Managing API Data Using your state management
  • Fetching Data from Odoo Efficiently
  •  Displaying Fetched Data in your ui

Let’s dive in.

1. Setting Up Your Flutter Project with your Getx

Add the required dependencies in pubspec.yaml

				
					 # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.6
  http: ^1.3.0
  get: ^4.7.2
				
			

Change MaterialApp into GetMaterialApp

				
					import 'package:get/get.dart';


void main() {
  runApp(const MyApp());
}


class MyApp extends StatelessWidget {
  const MyApp({super.key});


  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Flutter Getx Demo',
      theme: ThemeData(
     
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Getx Demo Home Page'),
    );
  }
}

				
			

2. Connecting Flutter to Odoo REST API

  1. Odoo uses RESTful APIs that return JSON responses. The base API URL follows this format
  2. To authenticate and fetch data, we need
    • Username (login)
    • Password (password)
  3. Create a service file api_service.dart to handle API requests
				
					class ApiService {
  final String baseUrl = "https://your-odoo-domain.com/jsonrpc";


  Future authenticate(String username, String password, String db) async {
    final response = await http.post(
      Uri.parse(baseUrl),
      headers: {"Content-Type": "application/json"},
      body: jsonEncode({
        "jsonrpc": "2.0",
        "method": "call",
        "params": {
          "service": "common",
          "method": "authenticate",
          "args": [db, username, password, {}]
        }
      }),
    );


    final data = jsonDecode(response.body);
    return data["result"]; // Returns user ID if successful
  }

				
			

3. Managing API Data Using GetX

Create a Controller to Handle API Calls.

				
					import 'package:get/get.dart';
import 'api_services.dart';


class AuthController extends GetxController {
  final ApiService _apiService = ApiService();
  var isAuthenticated = false.obs;
  var userId = 0.obs;


  Future login(String username, String password, String db) async {
    int? result = await _apiService.authenticate(username, password, db);
    if (result != null) {
      userId.value = result;
      isAuthenticated.value = true;
    } else {
      Get.snackbar("Error", "Invalid credentials");
    }
  }
}

				
			

4. Fetching Data from Odoo Efficiently

Update api_service.dart

				
					Future<List> getCustomers(int userId, String db) async {
    final response = await http.post(
      Uri.parse(baseUrl),
      headers: {"Content-Type": "application/json"},
      body: jsonEncode({
        "jsonrpc": "2.0",
        "method": "call",
        "params": {
          "service": "object",
          "method": "execute_kw",
          "args": [
            db,
            userId,
            "your_odoo_password",
            "res.partner",
            "search_read",
            [],
            {
              "fields": ["name", "email"]
            }
          ]
        }
      }),
    );


    final data = jsonDecode(response.body);
    return data["result"];
  }

				
			

5. Displaying Fetched Data in UI

Create a Customer Controller to manage API calls

				
					import 'package:get/get.dart';
import 'api_services.dart';


class CustomerController extends GetxController {
  final ApiService _apiService = ApiService();
  var customers = [].obs;


  Future loadCustomers(int userId, String db) async {
    var result = await _apiService.getCustomers(userId, db);
    customers.value = result;
  }
}

				
			

Update customer_screen.dart

				
					import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'customer_controller.dart';


class CustomerScreen extends StatelessWidget {
  CustomerScreen({super.key});


  final CustomerController controller = Get.put(CustomerController());


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Customers")),
      body: Obx(() {
        if (controller.customers.isEmpty) {
          return Center(child: CircularProgressIndicator());
        }
        return ListView.builder(
          itemCount: controller.customers.length,
          itemBuilder: (context, index) {
            var customer = controller.customers[index];
            return ListTile(
              title: Text(customer["name"]),
              subtitle: Text(customer["email"] ?? "No Email"),
            );
          },
        );
      }),
      floatingActionButton: FloatingActionButton(
        onPressed: () => controller.loadCustomers(1, "your_odoo_db"),
        child: Icon(Icons.refresh),
      ),
    );
  }
}



				
			

With GetX and Odoo API integration, we built a clean, efficient, and reactive state management system.

Why GetX & Odoo Are a Perfect Match

By integrating GetX with Odoo REST API, we created a reactive and efficient way to manage API data in Flutter apps. GetX simplifies logic separation, smooths UI updates, and lets you handle API interactions cleanly.

Whether you’re working on login systems, data fetching, or displaying lists from Odoo, GetX offers an easy learning curve and powerful performance.

This blog can act as your starting point for building scalable and dynamic Flutter apps that interact with enterprise backends like Odoo. As your app grows, you can easily extend this structure for more complex operations, permissions, and UI behaviors.

Pro Tip: Always separate your logic (controllers & services) from UI code for cleaner architecture and easier maintenance.

Picture of Irshad

Irshad

I’m Irshad, a passionate self-taught Flutter Developer Intern with strong problem-solving skills and a drive for continuous learning. I have experience building responsive user interfaces, implementing complex features, and collaborating effectively within teams.

Get a free quote