'Flutter SQLite error: I can't view inserts in screen

I want to manually add inserts from code to a table that was created using sqlite.

I would like to display a list with each item of elements that I inserted, but I can't display anything, even when I insert in the onCreate method

What am I doing wrong?

this is the code:

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)'
            );

        //insertando varios elementos pero no se visualiza en el listado cuando se corre la app
        //insert some values, but it can not visualice in list screen when run app
        await database.insert("Test1", {"id": 1});
        await database.insert("Test2", {"id": 2});
        await database.insert("Test3", {"id": 3});

        
        //insertando varios elementos pero no se visualiza en el listado cuando se corre la app
        //insert some values, but it can not visualice in list screen when run app
        await database.execute('INSERT INTO todos(id, title, description) VALUES (54, "titulo1" , "desc1"),(55, "titulo2" , "desc2")');
        //await database.execute("INSERT INTO todos(id, title, description) VALUES (12,'titulo1' , 'desc1'),(23,'titu2' ,'desc2'), (34,'titulo3' ,'desc3');");
      },
      version: 1,
    );
  }

  Future<void> inserttodo(todo todo) async {
    final db = await initializeDB();
    await db.insert(
      'todos',
      todo.toMap(),
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
  }
 //id INTEGER PRIMARY KEY, namec TEXT, entidadc TEXT, categoriac TEXT, tipoc TEXT, urlcursos TEXT, urlimgc TEXT, descripcionc TEXT
  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],
    );
  }
}

this is the lista_cursos.dart:

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Sqlite todos'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => AddScreen()),
          );
        },
        child: const Icon(Icons.add),
        backgroundColor: Colors.deepOrange,
      ),
      body: FutureBuilder<List<todo>>(
        future: _todo,
        builder: (BuildContext context, AsyncSnapshot<List<todo>> snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(
              child: const CircularProgressIndicator(),
            );
          } else if (snapshot.hasError) {
            return Text('Error: ${snapshot.error}');
          } else {
            final items = snapshot.data ?? <todo>[];
            return Scrollbar(
              child: RefreshIndicator(
                onRefresh: _onRefresh,
                child: ListView.builder(
                  itemCount: items.length,
                  itemBuilder: (BuildContext context, int index) {
                    return Dismissible(
                      direction: DismissDirection.startToEnd,
                      background: Container(
                        color: Colors.red,
                        alignment: Alignment.centerRight,
                        padding: const EdgeInsets.symmetric(horizontal: 10.0),
                        child: const Icon(Icons.delete_forever),
                      ),
                      key: ValueKey<int>(items[index].id),
                      onDismissed: (DismissDirection direction) async {
                        await handler.deletetodo(items[index].id);
                        setState(() {
                          items.remove(items[index]);
                        });
                      },
                      child: Card(
                          child: ListTile(
                        contentPadding: const EdgeInsets.all(8.0),
                        title: Text(items[index].title),
                        subtitle: Text(items[index].description.toString()),
                      )),
                    );
                  },
                ),
              ),
            );
          }
        },
      ),
    );
  }
}

when i run app, the list is empty:

enter image description here

enter image description here



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source