Last active
September 11, 2019 06:26
-
-
Save Dalmangyi/a2938f22b26cef84d80e4a5c60230e1f to your computer and use it in GitHub Desktop.
dart_sqflite_json_exam
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//lib/sqlite/db_helper.dart | |
import 'dart:io'; | |
import 'package:path_provider/path_provider.dart'; | |
import 'package:sqflite/sqflite.dart'; | |
import 'package:path/path.dart'; | |
import 'models/dog_model.dart'; | |
final String TableName = 'Dog'; | |
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 { | |
Directory documentsDirectory = await getApplicationDocumentsDirectory(); | |
String path = join(documentsDirectory.path, 'MyDogsDB.db'); | |
return await openDatabase( | |
path, | |
version: 1, | |
onCreate: (db, version) async { | |
await db.execute(''' | |
CREATE TABLE $TableName( | |
id INTEGER PRIMARY KEY, | |
name TEXT, | |
) | |
'''); | |
}, | |
onUpgrade: (db, oldVersion, newVersion){} | |
); | |
} | |
//Create | |
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.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.query(TableName); | |
List<Dog> list = res.isNotEmpty ? res.map((c) => Dog.fromJson(c)).toList() : []; | |
return list; | |
} | |
//Update | |
updateDog(Dog dog) async { | |
final db = await database; | |
var res = db.update(TableName, dog.toJson(), where: 'id = ?', whereArgs: [dog.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'); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//lib/sqlite/models/dog_model.dart | |
class Dog { | |
final int id; | |
final String name; | |
Dog({this.id, this.name}); | |
factory Dog.fromJson(Map<String, dynamic> json) => Dog( | |
id: json["id"], | |
name: json["name"] | |
); | |
Map<String, dynamic> toJson() => { | |
"id":id, | |
"name":name, | |
}; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//lib/main.dart | |
import 'package:flutter/material.dart'; | |
import 'sqlite/db_helper.dart'; | |
import 'sqlite/models/dog_model.dart'; | |
import 'dart:math'; | |
List<Dog> dogs = [ | |
Dog(name: '푸들이'), | |
Dog(name: '삽살이'), | |
Dog(name: '말티말티'), | |
Dog(name: '강돌이'), | |
Dog(name: '진져'), | |
Dog(name: '백구'), | |
]; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: MyHomePage(title: 'Dog Database'), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
MyHomePage({Key key, this.title}) : super(key: key); | |
final String title; | |
@override | |
_MyHomePageState createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text(widget.title), | |
), | |
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); | |
}, | |
child: Center(child: Text(item.name)), | |
); | |
}, | |
); | |
} | |
else | |
{ | |
return Center(child: CircularProgressIndicator(),); | |
} | |
}, | |
), | |
floatingActionButton: Column( | |
mainAxisSize: MainAxisSize.min, | |
children: <Widget>[ | |
FloatingActionButton( | |
child: Icon(Icons.refresh), | |
onPressed: () { | |
DBHelper().deleteAllDogs(); | |
setState(() {}); | |
}, | |
), | |
SizedBox(height: 8.0), | |
FloatingActionButton( | |
child: Icon(Icons.add), | |
onPressed: () { | |
Dog dog = dogs[Random().nextInt(dogs.length)]; | |
DBHelper().createData(dog); | |
setState(() {}); | |
}, | |
), | |
], | |
) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment