import 'package:flutter/material.dart';
import 'package:flutter_application_1/services/db_helper.dart';
// Here we are using a global variable. You can use something like
// get_it in a production app.
final dbHelper = DatabaseHelper();
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
// initialize the database
await dbHelper.init();
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'SQFlite Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List data = [];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('sqfliteby DeveloperCodez'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: List.generate(
data.length,
(index) => Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(data[index]['_id'].toString()),
Text(data[index]['name']),
Text(data[index]['written_by'])
],
)),
),
ElevatedButton(
onPressed: _insert,
child: const Text('insert'),
),
const SizedBox(height: 10),
ElevatedButton(
onPressed: _query,
child: const Text('query'),
),
const SizedBox(height: 10),
ElevatedButton(
onPressed: _update,
child: const Text('update'),
),
const SizedBox(height: 10),
ElevatedButton(
onPressed: _delete,
child: const Text('delete'),
),
],
),
),
);
}
void _insert() async {
// row to insert
Map<String, dynamic> row = {
DatabaseHelper.columnName: 'DeveloprCodez',
DatabaseHelper.columnAge: 24,
DatabaseHelper.coulumnWrittenBy: 'Flutter Tutorial'
};
final id = await dbHelper.insert(row);
debugPrint('inserted row id: $id');
_query();
}
void _query() async {
final allRows = await dbHelper.queryAllRows();
debugPrint('query all rows:');
// for (final row in allRows) {
// debugPrint(row.toString());
// }
setState(() {
data = allRows;
// print(data[0]['_id']);
});
}
void _update() async {
// row to update
Map<String, dynamic> row = {
DatabaseHelper.columnId: 1,
DatabaseHelper.columnName: 'developerCodez',
DatabaseHelper.columnAge: 30,
DatabaseHelper.coulumnWrittenBy: 'Flutter Tutorial for sqLite'
};
final rowsAffected = await dbHelper.update(row);
debugPrint('updated $rowsAffected row(s)');
_query();
}
void _delete() async {
// Assuming that the number of rows is the id for the last row.
final id = await dbHelper.queryRowCount();
final rowsDeleted = await dbHelper.delete(id);
debugPrint('deleted $rowsDeleted row(s): row $id');
_query();
}
}
0 Comments (Please let us know your query)