[flutter] sqlite db 사용하기

dev-nam 2022. 3. 9. 19:54

Flutter Sqlite DB 사용하기

간단한 데이터는 사용자 기기 로컬 저장소에 저장해서 관리하는게 효율적일 수 있다. 로컬 저장소 종류는 다양하지만 이번에는 Sqlite DB를 사용해서 데이터를 관리해보려고 한다.

 

패키지 설치

pubsepc.yaml 파일에 sqflite 패키지 코드를 추가한다. sqflite 버전은 플러터 패키지 사이트에서 가장 최신버전을 사용한다. (https://pub.dev/packages/sqflite)

dependencies:
  sqflite: ^2.0.2

커멘드 창에 다음 명령어를 입력해서 패키지 설치를 완료한다.

$ flutter pub get

 

패키지 불러오기

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

 

데이터베이스 생성

Future _openDb() async {  
  final databasePath = await getDatabasesPath();
  String path = join(databasePath, 'my_database.db');
  
  final db = await openDatabase(
    path,
    version: 1,
    onConfigure: (Database db) => {},
    onCreate: (Database db, int version) => {},
    onUpgrade: (Database db, int oldVersion, int newVersion) => {},
  );
}

 

테이블 생성하기 (Table)

Future _onCreate(Database db, int version) async {
  await db.execute('''
    CREATE TABLE IF NOT EXISTS posts (
      id INTEGER PRIMARY KEY,
      title TEXT NOT NULL,
      content TEXT NOT NULL,
      created_at TEXT NOT NULL
    )
  ''');
}

 

데이터 추가하기 (Insert)

Future add(item) async {
  final db = await _openDb();
  item.id = await db.insert(
    'posts',  // table name
    {           
      'title': 'new post ...',
      'content': 'this is add method',
      'created_at': '2022-01-01 00:00:00',
    },  // new post row data	
    conflictAlgorithm: ConflictAlgorithm.replace,
  );
  return item;
}

 

데이터 변경하기 (Update)

Future update(item) async {
  final db = await _openDb();
  await db.update(
    'posts',  // table name
    {
      'title': 'changed post title ...',
      'content': 'changed post content ...',
    },  // update post row data
    where: 'id = ?',
    whereArgs: [item.id],
  );
  return item;
}

 

데이터 삭제하기 (Delete)

Future<int> remove(int id) async {
  final db = await _openDb();
  await db.delete(
    'posts', // table name
    where: 'id = ?',
    whereArgs: [id],
  );
  return id;
}

 

전체 코드1  (post_helper.dart)

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

class PostHelper {
  // 데이터베이스를 시작한다.
  Future _openDb() async {  
    final databasePath = await getDatabasesPath();
    String path = join(databasePath, 'my_database.db');
  
    final db = await openDatabase(
      path,
      version: 1,
      onConfigure: (Database db) => {},
      onCreate: _onCreate,
      onUpgrade: (Database db, int oldVersion, int newVersion) => {},
    );
  }

  // 데이터베이스 테이블을 생성한다.
  Future _onCreate(Database db, int version) async {
    await db.execute('''
      CREATE TABLE IF NOT EXISTS posts (
        id INTEGER PRIMARY KEY,
        title TEXT NOT NULL,
        content TEXT NOT NULL,
        created_at TEXT NOT NULL
      )
    ''');
  }
  
  // 새로운 데이터를 추가한다.
  Future add(item) async {
    final db = await _openDb();
    item.id = await db.insert(
      'posts',  // table name
      {           
        'title': 'new post ...',
        'content': 'this is add method',
        'created_at': '2022-01-01 00:00:00',
      },  // new post row data	
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
    return item;
  }
  
  // 변경된 데이터를 업데이트한다.
  Future update(item) async {
    final db = await _openDb();
    await db.update(
      'posts',  // table name
      {
        'title': 'changed post title ...',
        'content': 'changed post content ...',
      },  // update post row data
      where: 'id = ?',
      whereArgs: [item.id],
    );
    return item;
  }
  
  // 데이터를 삭제한다.
  Future<int> remove(int id) async {
    final db = await _openDb();
    await db.delete(
      'posts', // table name
      where: 'id = ?',
      whereArgs: [id],
    );
    return id;
  }
}

 

전체 코드2 (post_page.dart)

// post_page.dart
import 'package:flutter/material.dart';
import 'package:blog_clone_app/helpers/post_helper.dart';

class PostPage extends StatefulWidget {
  const ({ Key? key }) : super(key: key);
  
  @override
  _State createState() => _State();
}

class _PostPageState extends State<PostPage> {
  late List _posts = [];

  // post 헬퍼 클래스를 초기화한다.
  final PostHelper _postHelper = PostHelper();
  
  // post 리스트를 조회한다.
  Future _getPosts() async {
    _posts = await _postHelper.getPosts();
  }
  
  // 새로운 post를 추가한다.
  Future _addPost() async {
    await _postHelper.add({
      'title': 'new post title ...',
      'content': 'new post content ...',
      'created_at': '2022-01-01 00:00:00',
    });
  }
  
  // 기존 post를 변경한다.
  Future _updatePost() async {
    await _postHelper.update({
      'id': 1,
      'title': 'changed post title ...',
      'content': 'changed post content ...',
    });
  }
  
  // post를 삭제한다.
  Future _removePost() async {
    await _postHelper.remove(1);
  }
  
  @override
  void initState() {
    super.initState();
    _getPosts();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ...,
    );
  }
}

 

반응형

'주제 > flutter' 카테고리의 다른 글

[flutter] cached_network_image package  (0) 2022.04.09
[flutter] 앱 테마 설정하기  (0) 2022.04.03
[flutter] Class.fromMap  (0) 2022.03.20
[flutter] datetime timestamp  (0) 2022.03.09
[flutter] container min-max width, height  (0) 2022.02.27