[flutter] 플러터(sqflite)와 RESTful API 연동하기

플러터(Flutter) 앱을 개발하다 보면 로컬 데이터베이스에 데이터를 저장하고 RESTful API를 통해 원격 서버에 데이터를 저장하고 불러오는 일이 있습니다. 이를 위해 플러터에서는 sqflite 패키지를 사용하여 로컬 데이터베이스를 구성하고, RESTful API를 호출하기 위해 http 패키지를 사용합니다.

1. sqflite를 이용한 로컬 데이터베이스 구성

먼저, sqflite 패키지를 이용하여 플러터 앱에 로컬 데이터베이스를 구성합니다.

import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

void main() async {
  final database = openDatabase(
    // Set the path to the database.
    join(await getDatabasesPath(), 'my_database.db'),
    // When the database is first created, create a table to store data.
    onCreate: (db, version) {
      return db.execute(
        "CREATE TABLE items(id INTEGER PRIMARY KEY, name TEXT, description TEXT)",
      );
    },
    // Set the version. This executes the onCreate function and provides a path to perform database upgrades and downgrades.
    version: 1,
  );

  // ...
}

2. RESTful API 호출

이제, http 패키지를 사용하여 RESTful API를 호출하여 원격 서버에 데이터를 저장하고 불러올 수 있습니다.

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

// Define the API endpoint.
final String apiUrl = 'https://example.com/api/items';

Future<List<dynamic>> fetchItems() async {
  final response = await http.get(Uri.parse(apiUrl));

  if (response.statusCode == 200) {
    // If the server returns a 200 OK response, parse the JSON data.
    return json.decode(response.body);
  } else {
    // If the server returns an error response, throw an exception.
    throw Exception('Failed to load items');
  }
}

Future<void> createItem(String name, String description) async {
  final response = await http.post(
    Uri.parse(apiUrl),
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, String>{
      'name': name,
      'description': description,
    }),
  );

  if (response.statusCode != 201) {
    // If the server returns an error response, throw an exception.
    throw Exception('Failed to create item');
  }
}

3. 연동 및 활용

로컬 데이터베이스에 저장된 데이터를 RESTful API를 통해 원격 서버에 동기화하거나, 원격 서버에 새로운 데이터를 추가하여 로컬 데이터베이스와 동기화할 수 있습니다. 이를 통해 효율적인 데이터 관리 및 동기화를 구현할 수 있습니다.

이처럼 플러터에서는 sqflite 패키지를 이용하여 로컬 데이터베이스를 구성하고, http 패키지를 이용하여 RESTful API를 호출하여 데이터를 관리하고 동기화할 수 있습니다. 이를 통해 안정적이고 효율적인 데이터 관리 및 연동이 가능합니다.

참고 자료

이상으로, 플러터(sqflite)와 RESTful API 연동하기에 관한 내용을 살펴보았습니다.