Tuesday, May 7, 2024

Flutter Database işlemleri

 main.dart

import 'package:flutter/material.dart';
import 'package:flutter_application_2/homepage.dart';

void main() {
  runApp(const MainApp());
}

class MainApp extends StatelessWidget {
  const MainApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: HomePage(),
    );
  }
}


homepage.dart

import 'package:flutter/material.dart';
import 'package:flutter_application_2/adduserpage.dart';
import 'package:flutter_application_2/dbhelper/dbhelper.dart';
import 'package:flutter_application_2/dbhelper/models/user.dart';
import 'package:flutter_application_2/updateuserpage.dart';
import 'package:sqflite/sqflite.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

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

class _MyWidgetState extends State<HomePage> {
  List<User> users = [];
  @override
  void initState() {
    super.initState();
    _loadUsers();
  }

  Future<void> _loadUsers() async {
    DbHelper db = DbHelper();
    users = await db.getUsers();
    print(users);
    setState(() {
      users = users;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
        itemCount: users.length,
        itemBuilder: (context, index) {
          User user = users[index];
          return ListTile(
            onTap: () => Navigator.of(context).push(MaterialPageRoute(
              builder: (context) => UpdateUserPage(user.id),
            )),
            title: Text("${user.id}. ${user.username}"),
            subtitle: Text("${user.ad} ${user.soyad}"),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
          onPressed: () {
            Navigator.of(context).push(MaterialPageRoute(
              builder: (context) => const AddUserPage(),
            ));
          },
          child: const Icon(Icons.add)),
    );
  }
}

adduserpage.dart

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_application_2/dbhelper/dbhelper.dart';
import 'package:flutter_application_2/dbhelper/models/user.dart';

class AddUserPage extends StatefulWidget {
  const AddUserPage({super.key});

  @override
  State<AddUserPage> createState() => _AddUserPageState();
}

class _AddUserPageState extends State<AddUserPage> {
  TextEditingController txtusername = TextEditingController();
  TextEditingController txtad = TextEditingController();
  TextEditingController txtpassword = TextEditingController();
  TextEditingController txtsoyad = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Yeni User EKLE"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(10.0),
        child: Column(children: [
          const SizedBox(
            height: 10,
          ),
          TextField(
              controller: txtusername,
              decoration: const InputDecoration(
                  border: OutlineInputBorder(), hintText: "Username")),
          const SizedBox(
            height: 10,
          ),
          TextField(
              controller: txtpassword,
              decoration: const InputDecoration(
                  border: OutlineInputBorder(), hintText: "Password")),
          const SizedBox(
            height: 10,
          ),
          TextField(
              controller: txtad,
              decoration: const InputDecoration(
                  border: OutlineInputBorder(), hintText: "Ad")),
          const SizedBox(
            height: 10,
          ),
          TextField(
              controller: txtsoyad,
              decoration: const InputDecoration(
                  border: OutlineInputBorder(), hintText: "Soyad")),
          const SizedBox(
            height: 10,
          ),
          ElevatedButton(
              onPressed: () {
                DbHelper db = DbHelper();
                db.insertUser(User(
                    ad: txtad.text,
                    soyad: txtsoyad.text,
                    username: txtusername.text,
                    password: txtpassword.text));
                Navigator.pop(context);
              },
              child: const Text("EKLE")),
        ]),
      ),
    );
  }
}

updateuserpage.dart

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_application_2/dbhelper/dbhelper.dart';
import 'package:flutter_application_2/dbhelper/models/user.dart';
import 'package:flutter_application_2/homepage.dart';

class UpdateUserPage extends StatefulWidget {
  UpdateUserPage(this.userid, {super.key});
  int? userid;
  @override
  State<UpdateUserPage> createState() => _UpdateUserPageState();
}

class _UpdateUserPageState extends State<UpdateUserPage> {
  TextEditingController txtusername = TextEditingController();
  TextEditingController txtad = TextEditingController();
  TextEditingController txtpassword = TextEditingController();
  TextEditingController txtsoyad = TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _loadUser();
  }

  Future<void> _loadUser() async {
    DbHelper db = DbHelper();
    User? user = await db.getUser(widget.userid!);
    setState(() {
      txtad.text = user!.ad;
      txtsoyad.text = user.soyad;
      txtusername.text = user.username;
      txtpassword.text = user.password;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("User Düzenle"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(10.0),
        child: Column(children: [
          const SizedBox(
            height: 10,
          ),
          TextField(
              controller: txtusername,
              decoration: const InputDecoration(
                  border: OutlineInputBorder(), hintText: "Username")),
          const SizedBox(
            height: 10,
          ),
          TextField(
              controller: txtpassword,
              decoration: const InputDecoration(
                  border: OutlineInputBorder(), hintText: "Password")),
          const SizedBox(
            height: 10,
          ),
          TextField(
              controller: txtad,
              decoration: const InputDecoration(
                  border: OutlineInputBorder(), hintText: "Ad")),
          const SizedBox(
            height: 10,
          ),
          TextField(
              controller: txtsoyad,
              decoration: const InputDecoration(
                  border: OutlineInputBorder(), hintText: "Soyad")),
          const SizedBox(
            height: 10,
          ),
          ElevatedButton(
              onPressed: () {
                DbHelper db = DbHelper();
                User user = User(
                    id: widget.userid,
                    ad: txtad.text,
                    soyad: txtsoyad.text,
                    password: txtpassword.text,
                    username: txtusername.text);
                db.updateUser(user);
                Navigator.of(context).push(
                    MaterialPageRoute(builder: (context) => const HomePage()));
              },
              child: const Text("GÜNCELLE")),
        ]),
      ),
    );
  }
}


dbhelper.dart


import 'dart:async';
import 'dart:io';
import 'package:flutter_application_2/dbhelper/models/user.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';

class DbHelper {
  static const String databaseName = "mydb2.db";
  static const int databaseVersion = 1;

  Database? _db;

  Future<Database?> get db async {
    if (_db != null) return _db;
    _db = await _initDb();
    return _db;
  }

  _initDb() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, databaseName);
    return await openDatabase(path, version: databaseVersion,
        onCreate: (db, version) {
      db.execute(
          "CREATE TABLE users (id INTEGER PRIMARY KEY, ad TEXT, soyad TEXT, username TEXT, password TEXT)");
      db.execute(
          "INSERT INTO users (ad, soyad, username, password) VALUES (?, ?, ?, ?)",
          ["Recep", "ÖZEN", "user1", "1234"]);
      db.execute(
          "INSERT INTO users (ad, soyad, username, password) VALUES (?, ?, ?, ?)",
          ["Ahmet", "TUNA", "user2", "1234"]);
      db.execute(
          "INSERT INTO users (ad, soyad, username, password) VALUES (?, ?, ?, ?)",
          ["Ali", "ÖZER", "user3", "1234"]);
      db.execute(
          "INSERT INTO users (ad, soyad, username, password) VALUES (?, ?, ?, ?)",
          ["Kazım", "SELİM", "user4", "1234"]);
    });
  }

  // Örnek: Kullanıcı Ekleme
  Future<int> insertUser(User user) async {
    final db = await this.db;
    int id = await db!.insert("users", user.toMap());
    return id;
  }

  // Örnek: Kullanıcı Okuma
  Future<List<User>> getUsers() async {
    final db = await this.db;
    List<Map<String, dynamic>> rows = await db!.query("users");
    List<User> users = rows.map((row) => User.fromMap(row)).toList();
    return users;
  }

  Future<User?> getUser(int id) async {
    final db = await this.db;
    List<Map<String, dynamic>> rows =
        await db!.query("users", where: "id=?", whereArgs: [id]);
    User? user = rows.map((row) => User.fromMap(row)).toList().firstOrNull;
    return user;
  }

  Future<int> updateUser(User user) async {
    final db = await this.db;

    return await db!
        .update("users", user.toMap(), where: "id=?", whereArgs: [user.id]);
  }
}

user.dart

class User {
  int? id;
  String ad;
  String soyad;
  String username;
  String password;

  User({
    this.id,
    required this.ad,
    required this.soyad,
    required this.username,
    required this.password,
  });

  factory User.fromMap(Map<String, dynamic> map) => User(
      id: map['id'] as int,
      ad: map['ad'] as String,
      soyad: map['soyad'] as String,
      username: map['username'] as String,
      password: map['password'] as String);

  Map<String, dynamic> toMap() => {
        'id': id,
        'ad': ad,
        'soyad': soyad,
        'username': username,
        'password': password,
      };
}


eklenecek dependeciesler

  path: ^1.8.3
  path_provider: ^2.1.3
  sqflite: ^2.3.2





No comments: