I'm developing a simple app that displays a list of items as a to-do app, but I don't want the user to write the instances to record the to-dos, but instead create those instances myself from code.
I want to make inserts or instances from code, like title, description, etc... so that they are saved locally, I don't want users to create the to-do instances themselves, I just want to create inserts one by one.
this is my code to add instances to SQLite:
class _AddScreenState extends State<AddScreen> {
final _formKey = GlobalKey<FormState>();
String title = "";
String description = "";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Add todo'),
),
body: Center(
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
TextFormField(
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter some text';
}
return null;
},
decoration: const InputDecoration(
hintText: 'title',
),
onChanged: (value) {
setState(() {
title = value;
});
},
),
TextFormField(
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter some text';
}
return null;
},
decoration: const InputDecoration(
hintText: 'Description',
),
onChanged: (value) {
setState(() {
description = value;
});
},
),
ElevatedButton(
onPressed: () async {
if (_formKey.currentState!.validate()) {
await DatabaseHandler()
.inserttodo(todo(
title: title,
description: description,
id: Random().nextInt(50)))
.whenComplete(() => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ListScreen()),
));
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Processing Data')),
);
}
},
child: const Text(
'Add',
style: TextStyle(
fontSize: 20,
),
),
),
],
),
),
),
);
}
}
this is my databaseHandler class
class DatabaseHandler {
Future<Database> initializeDB() async {
String path = await getDatabasesPath();
return openDatabase(
join(path, 'tododatabase.db'),
onCreate: (database, version) async {
await database.execute(
'CREATE TABLE todos(id INTEGER PRIMARY KEY, title TEXT, description TEXT)',
);
},
version: 1,
);
}
Future<void> inserttodo(todo todo) async {
final db = await initializeDB();
await db.insert(
'todos',
todo.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
Future<List<todo>> todos() async {
final db = await initializeDB();
final List<Map<String, dynamic>> queryResult = await db.query('todos');
return queryResult.map((e) => todo.fromMap(e)).toList();
}
Future<void> deletetodo(int id) async {
final db = await initializeDB();
await db.delete(
'todos',
where: 'id = ?',
whereArgs: [id],
);
}
}
onCreate?