hive implementation
save todo in hive first release
This commit is contained in:
95
lib/pages/home_page.dart
Normal file
95
lib/pages/home_page.dart
Normal file
@@ -0,0 +1,95 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:todo/data/database.dart';
|
||||
import 'package:todo/utils/dialog_box.dart';
|
||||
import 'package:todo/utils/todo_tile.dart';
|
||||
import 'package:hive_flutter/hive_flutter.dart';
|
||||
|
||||
class MyHomePage extends StatefulWidget {
|
||||
const MyHomePage({Key? key, required this.title}) : super(key: key);
|
||||
|
||||
final String title;
|
||||
|
||||
@override
|
||||
State<MyHomePage> createState() => _MyHomePageState();
|
||||
}
|
||||
|
||||
class _MyHomePageState extends State<MyHomePage> {
|
||||
//reference hive todo box
|
||||
final _myBox = Hive.box('todoBox');
|
||||
|
||||
ToDoDataBase db = ToDoDataBase();
|
||||
|
||||
final _controller = TextEditingController();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
// TODO: implement initState
|
||||
// first time
|
||||
if (_myBox.get('todos') == null) {
|
||||
db.createInitialData();
|
||||
} else {
|
||||
db.loadData();
|
||||
}
|
||||
|
||||
super.initState();
|
||||
}
|
||||
|
||||
void checkBoxChanged(bool? value, int index) {
|
||||
setState(() {
|
||||
db.todoList[index][1] = !db.todoList[index][1];
|
||||
});
|
||||
db.updateData();
|
||||
}
|
||||
|
||||
void saveNewTask() {
|
||||
setState(() {
|
||||
db.todoList.add([_controller.text, false]);
|
||||
_controller.clear();
|
||||
});
|
||||
db.updateData();
|
||||
Navigator.of(context).pop();
|
||||
}
|
||||
|
||||
void createNewTask() {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) {
|
||||
return DialogBox(
|
||||
controller: _controller,
|
||||
onCancel: () => Navigator.of(context).pop(),
|
||||
onSave: saveNewTask,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
void deleteTask(int index) {
|
||||
setState(() {
|
||||
db.todoList.removeAt(index);
|
||||
});
|
||||
db.updateData();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text(widget.title),
|
||||
),
|
||||
body: ListView.builder(
|
||||
itemCount: db.todoList.length,
|
||||
itemBuilder: (context, index) {
|
||||
return ToDoTile(
|
||||
taskName: db.todoList[index][0],
|
||||
taskCompleted: db.todoList[index][1],
|
||||
onChanged: (value) => checkBoxChanged(value, index),
|
||||
deleteFunction: (context) => deleteTask(index),
|
||||
);
|
||||
}),
|
||||
floatingActionButton: FloatingActionButton(
|
||||
onPressed: createNewTask,
|
||||
tooltip: 'Increment',
|
||||
child: const Icon(Icons.add),
|
||||
), // This trailing comma makes auto-formatting nicer for build methods.
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user