Flutter With Sqflite Database Tutorial

Add following plugin in pubspec.yaml file:

  • sqflite: ^2.0.0+3
  • path_provider: ^2.0.1

main.dart

import 'package:databasedemo/operations.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController rollcontroller = TextEditingController();
  TextEditingController namecontroller = TextEditingController();
  TextEditingController markscontroller = TextEditingController();
  FocusNode f1 = FocusNode();
  FocusNode f2 = FocusNode();
  FocusNode f3 = FocusNode();
  Widget myfuturewidget;

  @override
  void initState() {
    myfuturewidget = Container();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Form Data"),
      ),
      body: SingleChildScrollView(
        child: Container(
          margin: EdgeInsets.all(20),
          child: Column(
            children: [
              TextFormField(
                decoration: InputDecoration(
                  labelText: "Enter Roll",
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(4.0)),
                ),
                keyboardType: TextInputType.number,
                controller: rollcontroller,
                focusNode: f1,
              ),
              SizedBox(
                height: 10,
              ),
              TextFormField(
                decoration: InputDecoration(
                  labelText: "Enter Name",
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(4.0)),
                ),
                keyboardType: TextInputType.text,
                controller: namecontroller,
                focusNode: f2,
              ),
              SizedBox(
                height: 10,
              ),
              TextFormField(
                decoration: InputDecoration(
                  labelText: "Enter Marks",
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(4.0)),
                ),
                keyboardType: TextInputType.number,
                controller: markscontroller,
                focusNode: f3,
              ),
              SizedBox(
                height: 10,
              ),
              ButtonBar(
                alignment: MainAxisAlignment.start,
                children: [
                  Container(
                    child: ElevatedButton(
                      onPressed: () {
                        if (valid()) {
                          Student student = Student(
                              roll: int.parse(roll),
                              name: name,
                              marks: double.parse(marks));
                          MyDatabase.myDatabase
                              .insert(student)
                              .then((value) => print(value));
                        }
                      },
                      child: Text("Insert"),
                    ),
                    margin: EdgeInsets.all(5),
                  ),
                  Container(
                    child: ElevatedButton(
                      onPressed: () {
                        if (valid()) {
                          MyDatabase.myDatabase
                              .fetchSingleStudent(roll)
                              .then((value) => print(value.name));
                        }
                      },
                      child: Text("Fetch By Roll"),
                    ),
                    margin: EdgeInsets.all(5),
                  ),
                  Container(
                    child: ElevatedButton(
                      onPressed: () {
                       
                        setState(() {
                          myfuturewidget = getData();
                        });
                      },
                      child: Text("Fetch All"),
                    ),
                    margin: EdgeInsets.all(5),
                  ),
                ],
              ),
              myfuturewidget,
            ],
          ),
        ),
      ),
    );
  }

  Widget getData() {
    return FutureBuilder(
      future: MyDatabase.myDatabase.getAllUsers(),
      builder: (context, snapshot) {
        return ListView.builder(
          shrinkWrap: true,
          itemCount: snapshot.data.length,
          itemBuilder: (context, index) {
            Student student = snapshot.data[index];
            return ListTile(
              title: Center(
                child: Text(student.name),
              ),
              
              leading: Text(student.roll.toString()),
              trailing: Text(student.marks.toString()),
            );
          },
        );
      },
    );
  }

  var name, roll, marks;

  bool valid() {
    roll = rollcontroller.text;
    name = namecontroller.text;
    marks = markscontroller.text;
    if (roll == "") {
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text('please enter roll')));
      FocusScope.of(context).requestFocus(f1);
      return false;
    } else if (name == "") {
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text('please enter name')));
      FocusScope.of(context).requestFocus(f2);
      return false;
    } else if (marks == "") {
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text('please enter marks')));
      FocusScope.of(context).requestFocus(f3);
      return false;
    } else {
      return true;
    }
  }
}

class Student {
  int roll;
  String name;
  double marks;

  Student({this.roll, this.name, this.marks});

  Student.fromMap(Map<String, dynamic> map)
      : roll = map['roll'],
        name = map['name'],
        marks = map['marks'];

  Map<String, dynamic> toMap() {
    return {
      'roll': roll,
      'name': name,
      'marks': marks,
    };
  }
}
  

operations.dart

import 'dart:convert';
import 'dart:io';
import 'package:databasedemo/main.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class MyDatabase{

  static const DATABASE_NAME = "mycollege.db";
  static const TABLE_NAME = "students";
  static const NAME = "name";
  static const ROLL = "roll";
  static const MARKS = "marks";
  static const DATABASE_VERSION = 1;

  MyDatabase._();

  static MyDatabase myDatabase = MyDatabase._();
  static Database _database;

  Future<Database> getDatabase() async {
    if (_database != null) return _database;
    _database = await _initDB();
    print(_database);
    return _database;
  }

  _initDB() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, DATABASE_NAME);
    return await openDatabase(path,
        version: 1, onOpen: (db) {}, onCreate: _onCreate);
  }

  _onCreate(Database db, int version) async {
    await db.execute("CREATE TABLE $TABLE_NAME ("
        "$ROLL int primary key,"
        "$NAME TEXT,"
        "$MARKS double)");
  }

  Future<int> insert(Student student)async{
    final Database db =await getDatabase();
    print(db);
    return await db.insert(
      '$TABLE_NAME',
      student.toMap(),
      conflictAlgorithm: ConflictAlgorithm.replace,
    );

  }

  Future<List<Student>> getAllUsers()async{
    final db = await getDatabase();
    final List<Map<String, dynamic>> maps = await db.query('$TABLE_NAME');
    List<Student> users = [];
    for (Map map in maps) {
    users.add(Student.fromMap(map));
    }
    return users;
  }

  Future<Student> fetchSingleStudent(String roll)async{
    final Database db =await getDatabase();
    var res=await db.query('$TABLE_NAME',where:'$ROLL=?'
    ,whereArgs:[int.parse(roll)]);
    Student student=Student.fromMap(res.first);
    return student;
  }

}
  

No comments: