* models\dog_model.dart
class Dog {
final int id;
final String name;
final String content;
final bool active;
Dog({this.id, this.name, this.content, this.active});
}
- Map형태로 바꾸기
class Dog {
final int id;
final String name;
final String content;
final bool active;
Dog({this.id, this.name, this.content, this.active});
factory Dog.fromJson(Map<String, dynamic> json) => Dog(
id: json["id"],
name: json["name"],
content: json["content"],
active: json["active"]);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"content": content,
"active": active,
};
}
* sqliste\db_helper.dart
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:sql_example/models/dog_model.dart';
final String TableName = 'TodsTBL';
class DBHelper {
DBHelper._();
static final DBHelper _db = DBHelper._();
factory DBHelper() => _db;
static Database _database;
Future<Database> get database async {
if (_database != null) return _database;
_database = await initDB();
return _database;
}
initDB() async {
return openDatabase(
join(await getDatabasesPath(), 'MyTodosDB.db'),
onCreate: (db, version) {
return db.execute('''
CREATE TABLE $TableName(
id INTEGER PRIMARY KEY,
name TEXT,
content TEXT,
active BOOL)
''');
},
onUpgrade: (db, oldVersion, newVersion) {},
version: 1,
);
}
//Create
createData(Dog mytodo) async {
final db = await database;
var res = await db.rawInsert(
'INSERT INTO $TableName(name,content,active) VALUES(?,?,?)',
[mytodo.name, mytodo.content, mytodo.active]);
print("active값:" + mytodo.active.toString());
return res;
}
---------------------------------------------------------------
* map형태로 바꾸고 insert 로 사용 (↑↑↑ 같은기능)
---------------------------------------------------------------
createData(Dog dog) async {
final db = await database;
var res = await db.insert(TableName, dog.toJson());
return res;
}
---------------------------------------------------------------
//Read
getDog(int id) async {
final db = await database;
var res = await db.rawQuery('SELECT * FROM $TableName WHERE id = ?', [id]);
return res.isNotEmpty
? Dog(
id: res.first['id'],
name: res.first['name'],
content: res.first['content'],
active: res.first['active'] == 0 ? false : true)
: Null;
}
------------------------------------------------------------------------------------
* query 사용 (↑↑↑ 같은기능)
------------------------------------------------------------------------------------
getDog(int id) async {
final db = await database;
var res = await db.query(TableName, where: 'id = ?', whereArgs: [id]);
return res.isNotEmpty ? Dog.fromJson(res.first) : Null;
}
-----------------------------------------------------------------------------------
//Read All
Future<List<Dog>> getAllDogs() async {
final db = await database;
var res = await db.rawQuery('SELECT * FROM $TableName');
print("readall" + res.toString());
List<Dog> list = res.isNotEmpty
? res
.map((c) => Dog(
id: c['id'],
name: c['name'],
content: c['content'],
active: c['active'] == 0 ? false : true, //---> bool일때 구문해줘야 에러안남
))
.toList()
: [];
return list;
}
------------------------------------------------------------------------------------
* query 사용 ↑↑↑ 같은기능
------------------------------------------------------------------------------------
Future<List<Dog>> getAllDogs() async {
final db = await database;
var res = await db.query(TableName);
return List.generate(res.length, (i) {
bool active = res[i]['active'] == 1 ? true : false;
return Dog(
name: res[i]['name'].toString(),
content: res[i]['content'].toString(),
active: active,
id: res[i]['id']);
});
}
------------------------------------------------------------------------------------
//Delete
deleteDog(int id) async {
final db = await database;
var res = db.rawDelete('DELETE FROM $TableName WHERE id = ?', [id]);
return res;
}
------------------------------------------------------------------------------------
* Delete사용 ↑↑↑ 같은기능
------------------------------------------------------------------------------------
deleteDog(int id) async {
final db = await database;
var res = db.delete(TableName, where: 'id = ?', whereArgs: [id]);
return res;
}
------------------------------------------------------------------------------------
//Delete All
deleteAllDogs() async {
final db = await database;
db.rawDelete('DELETE FROM $TableName');
}
}
* dogList.dart
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:sql_example/models/dog_model.dart';
import 'package:sql_example/slqlite/db_helper.dart';
List<Dog> dogs = [
Dog(name: '푸들이', content: '내용1', active: false),
Dog(name: '삽살이', content: '내용2', active: false),
Dog(name: '말티말티', content: '내용3', active: false),
Dog(name: '강돌이', content: '내용4', active: false),
Dog(name: '진져', content: '내용5', active: false),
Dog(name: '백구', content: '내용6', active: false),
];
class DogList extends StatefulWidget {
@override
_DogListState createState() => _DogListState();
}
class _DogListState extends State<DogList> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("doglist"),
),
body: FutureBuilder(
future: DBHelper().getAllDogs(),
builder: (BuildContext context, AsyncSnapshot<List<Dog>> snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
Dog item = snapshot.data[index];
return Dismissible(
key: UniqueKey(),
onDismissed: (direction) {
DBHelper().deleteDog(item.id);
setState(() {});
},
child: Center(
child: Row(
children: [
Text(item.name),
SizedBox(width: 20),
Text(item.content),
SizedBox(width: 20),
Text(item.active.toString()),
],
)),
);
},
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
),
floatingActionButton: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
FloatingActionButton(
child: Icon(Icons.refresh),
onPressed: () {
//모두 삭제 버튼
DBHelper().deleteAllDogs();
setState(() {});
},
heroTag: null,
),
SizedBox(height: 8.0),
FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
//추가 버튼
print('추가');
Dog mytodo = dogs[Random().nextInt(dogs.length)];
DBHelper().createData(mytodo);
setState(() {});
},
heroTag: null,
),
],
),
);
}
}
'코딩(개발) > Flutter' 카테고리의 다른 글
todolist(firebase) step2 (0) | 2021.03.12 |
---|---|
todolist(firebase) step1 (0) | 2021.03.10 |
sqflite (0) | 2021.03.05 |
chatting ui (0) | 2021.03.05 |
ListView / AnimateList (0) | 2021.03.04 |
댓글