0

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],
    );
  }
}
3
  • 1
    Why not create them inside onCreate? Commented Mar 4, 2022 at 1:45
  • it sounds fine, but i have not idea how to make that Commented Mar 4, 2022 at 1:53
  • may be is only make multiples "inserts" of objects inside a ListView ListTile Commented Mar 4, 2022 at 1:53

1 Answer 1

1

Run a query for each row before creation.

onCreate: (database, version) async {
        await database.execute(
          'CREATE TABLE todos(id INTEGER PRIMARY KEY, title TEXT, description TEXT)',
        );
        await database.execute(
          'INSERT INTO todos(id, title, description)
           VALUES (value1,value2 ,...),
                 (value1,value2 ,...),
                 (value1,value2 ,...);'
        );
      },
Sign up to request clarification or add additional context in comments.

5 Comments

thanks, can i make multiple inserts, inside same method?, like: 'INSERT INTO todos(id, title, description) VALUES(1, "first", "description")', 'INSERT INTO todos(id, title, description) VALUES(1, "second", "description")', 'INSERT INTO todos(id, title, description) VALUES(1, "third", "description")', ...
@MrK Updated the answer to insert multiple values in the same query.
Thanks. is that id automatic? or do I have to write one by one in each value
You can use sqlite's autoincrement on table creation sqlitetutorial.net/sqlite-autoincrement
i've implemented that code, but i can not see that values in the list screen, thats not work for me, sorry

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.