반응형

패키지 설치

 

1. sqflite

flutter pub add sqflite

https://pub.dev/packages/sqflite/install

 

2. path_provider

flutter pub add path_provider

https://pub.dev/packages/path_provider/install

 

3. path

flutter pub add path

https://pub.dev/packages/path/install

 

 

user.dart

class User {
  int? userId;
  String displayName;

  User({this.userId, required this.displayName});
}

 

db_helper.dart

import 'dart:io';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:sqflite_test/user.dart';

const String tableName = 'Users';

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, 'UserInfoDB.db');

    return await openDatabase(path, version: 1, onCreate: (db, version) async {
      await db.execute('''
          CREATE TABLE $tableName (
            userId INTEGER PRIMARY KEY,
            displayName TEXT
          )
        ''');
    }, onUpgrade: (db, oldVersion, newVersion) {});
  }

  createData(User user) async {
    final db = await database;
    var res = await db.rawInsert(
        'INSERT INTO $tableName(displayName) VALUES(?)', [user.displayName]);
    return res;
  }

  getUser(int userId) async {
    final db = await database;
    var res = await db
        .rawQuery('SELECT * FROM $tableName WHERE userId = ?', [userId]);
    return res.isNotEmpty
        ? User(
            userId: res.first['userId'] as int,
            displayName: res.first['displayName'] as String)
        : Null;
  }

  Future<List<User>> getAllUsers() async {
    final db = await database;
    var res = await db.rawQuery('SELECT * FROM $tableName');
    List<User> list = res.isNotEmpty
        ? res
            .map((c) => User(
                userId: c['userId'] as int,
                displayName: c['displayName'] as String))
            .toList()
        : [];

    return list;
  }

  deleteUser(int userId) async {
    final db = await database;
    var res = db.rawDelete('DELETE FROM $tableName WHERE userId = ?', [userId]);
    return res;
  }

  deleteAllUsers() async {
    final db = await database;
    db.rawDelete('DELETE FROM $tableName');
  }

  updateUser(User user) async {
    final db = await database;
    var res = db.rawUpdate(
        'UPDATE $tableName SET displayName = ? WHERE userId = ?',
        [user.displayName, user.userId]);
    return res;
  }
}

 

main.dart

import 'package:flutter/material.dart';
import 'package:sqflite_test/add_page.dart';
import 'package:sqflite_test/edit_page.dart';
import 'package:sqflite_test/home_page.dart';

void main() {
  runApp(MaterialApp(
    initialRoute: '/',
    routes: {
      '/': (context) => const HomePage(),
      '/add': (context) => const AddPage(),
      '/edit': (context) => const EditPage(),
    },
  ));
}

 

home_page.dart

import 'package:flutter/material.dart';
import 'package:sqflite_test/User.dart';
import 'package:sqflite_test/db_helper.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('SQLite'),
      ),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add),
        onPressed: () async {
          dynamic ret = await Navigator.pushNamed(context, '/add');
          if (ret != null) {
            User user = ret as User;
            DBHelper().createData(user);
            setState(() {});
          }
        },
      ),
      body: FutureBuilder(
        future: DBHelper().getAllUsers(),
        builder: (BuildContext context, AsyncSnapshot<List<User>> snapshot) {
          if (snapshot.hasData) {
            return ListView.builder(
              itemCount: snapshot.data!.length,
              itemBuilder: (BuildContext context, int index) {
                User item = snapshot.data![index];

                return Card(
                  child: ListTile(
                    onTap: () async {
                      await Navigator.pushNamed(context, '/edit',
                          arguments: item);
                      setState(() {});
                    },
                    onLongPress: () async {
                      await DBHelper().deleteUser(item.userId!);
                      setState(() {});
                    },
                    title: Text(item.displayName),
                  ),
                );
              },
            );
          } else {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      ),
    );
  }
}

 

 

add_page.dart

import 'package:flutter/material.dart';
import 'package:sqflite_test/User.dart';

class AddPage extends StatefulWidget {
  const AddPage({Key? key}) : super(key: key);

  @override
  State<AddPage> createState() => _AddPageState();
}

class _AddPageState extends State<AddPage> {
  final TextEditingController _textController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('추가'),
      ),
      body: Column(
        children: [
          TextField(
            controller: _textController,
            decoration: const InputDecoration(
              hintText: '이름을 입력하세요.',
              border: OutlineInputBorder(), //외곽선
            ),
          ),
          ElevatedButton(
              onPressed: () {
                Navigator.pop(context, User(displayName: _textController.text));
              },
              child: const Text('완료')),
        ],
      ),
    );
  }
}

 

edit_page.dart

import 'package:flutter/material.dart';
import 'package:sqflite_test/User.dart';
import 'package:sqflite_test/db_helper.dart';

class EditPage extends StatefulWidget {
  const EditPage({Key? key}) : super(key: key);

  @override
  State<EditPage> createState() => _EditPageState();
}

class _EditPageState extends State<EditPage> {
  final TextEditingController _textController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    User user = ModalRoute.of(context)!.settings.arguments as User;
    _textController.text = user.displayName;

    return Scaffold(
      appBar: AppBar(
        title: const Text('수정'),
      ),
      body: Column(
        children: [
          TextField(
            controller: _textController,
            decoration: const InputDecoration(
              hintText: '이름을 입력하세요.',
              border: OutlineInputBorder(), //외곽선
            ),
          ),
          ElevatedButton(
              onPressed: () {
                user.displayName = _textController.text;
                DBHelper().updateUser(user);
                Navigator.pop(context);
              },
              child: const Text('수정')),
        ],
      ),
    );
  }
}
반응형

+ Recent posts