[Flutter] 메모 5
2020. 12. 27. 19:28ㆍFlutter Mobile App/Flutter 메모 앱
반응형
Sqlite로 메모 저장 기능구현
lib
> model
- memo.dart
> repository
- db_helper.dart
> screens
- home_page.dart
- write_page.dart
모델 작성
model/memo.dart
더보기
class Memo {
final int id;
final String title;
final String text;
final String createdTime;
final String editedTime;
Memo({this.id, this.title, this.text, this.createdTime, this.editedTime});
Map<String, dynamic> toMap() {
return {
'id': id,
'title': title,
'text': text,
'createdTime': createdTime,
'editedTime': editedTime
};
}
@override
String toString() {
// TODO: implement toString
return """
Memo {
id: $id,
title: $title,
text: $text,
createdTime: $createdTime,
editedTime: $editedTime
}
""";
}
}
pubspec.yaml 에 sqflite 모듈 추가
리포지토리
repository/db_helper.dart
더보기
import 'package:memo/model/memo.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
final String tableName = 'memos';
class DBHelper {
var _db;
// DB 조회
Future<Database> get database async {
if (_db != null) return _db;
_db = openDatabase(
// DB 경로 지정 : path 패키지의 join 함수 사용
join(await getDatabasesPath(), 'memos.db'),
onCreate: (db, version) {
return db.execute(
"""
CREATE TABLE memos(
id INTEGER PRIMARY KEY,
title TEXT,
text TEXT,
createdTime TEXT,
editedTime TEXT
)
""",
);
},
// DB 업그레이드 / 다운그레이드를 수행하기 위한 경로 제공
version: 1,
);
return _db;
}
// 메모 등록
Future<void> insertMemo(Memo memo) async {
final db = await database;
await db.insert(
tableName,
memo.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
// 메모 리스트
Future<List<Memo>> selectMemos() async {
final db = await database;
final List<Map<String, dynamic>> maps = await db.query('memos');
return List.generate(maps.length, (i) {
return Memo(
id: maps[i]['id'],
title: maps[i]['title'],
text: maps[i]['text'],
createdTime: maps[i]['createdTime'],
editedTime: maps[i]['editedTime'],
);
});
}
Future<void> updateMemo(Memo memo) async {
final db = await database;
await db.update(
tableName,
memo.toMap(),
where: "id = ?",
whereArgs: [memo.id],
);
}
Future<void> deleteMemo(int id) async {
final db = await database;
await db.delete(
tableName,
where: "id = ?",
whereArgs: [id],
);
}
}
작성 페이지
screens/write_page.dart
더보기
import 'package:flutter/material.dart';
import 'package:memo/model/memo.dart';
import 'package:memo/repository/db_helper.dart';
// ignore: must_be_immutable
class WritePage extends StatelessWidget {
String title = '';
String text = '';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: [
IconButton(
icon: const Icon(Icons.delete),
onPressed: () {
print('삭제 아이콘 클릭');
},
),
IconButton(
icon: const Icon(Icons.save),
onPressed: () {
print('저장 아이콘 클릭');
saveDB();
},
)
],
),
body: Padding(
padding: EdgeInsets.all(20),
child: Column(
children: [
TextField(
onChanged: (String title) {
this.title = title;
},
style: TextStyle(fontSize: 30, fontWeight: FontWeight.w500),
keyboardType: TextInputType.multiline,
maxLines: null,
decoration: InputDecoration(hintText: '메모 제목을 입력하세요.'),
),
Padding(
padding: EdgeInsets.all(10),
),
TextField(
onChanged: (String text) {
this.text = text;
},
keyboardType: TextInputType.multiline,
maxLines: null,
decoration: InputDecoration(hintText: '메모 내용을 입력하세요.'),
),
],
),
),
);
}
Future<void> saveDB() async {
DBHelper dbHelper = DBHelper();
var memo = Memo(
id: 3,
title: this.title,
text: this.text,
createdTime: DateTime.now().toString(),
editedTime: DateTime.now().toString(),
);
await dbHelper.insertMemo(memo);
print('저장하기');
print(await dbHelper.selectMemos());
}
}
반응형
'Flutter Mobile App > Flutter 메모 앱' 카테고리의 다른 글
[Flutter] 메모 7 (0) | 2020.12.27 |
---|---|
[Flutter] 메모 6 (0) | 2020.12.27 |
[Flutter] 메모 4 (0) | 2020.12.27 |
[Flutter] 메모 3 (0) | 2020.12.27 |
[Flutter] 메모 2 (0) | 2020.12.27 |