es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Future<>> no es un subtipo del tipo List.

Estoy obteniendo los datos de SQLite y tratando de establecerlos en un List view, pero estoy obteniendo un error:

    type 'Future>' no es un subtipo de tipo 'List'

Aquí está mi función de consulta de SQLite:

Future> leerTodasLasNotas() async {
final db = await instancia.database;

final orderBy = '${NotaCampos.tiempoAgregado} ASC';

final resultado = await db?.query(tablaNotas, orderBy: orderBy);

return resultado!.map((json) => Nota.fromJson(json)).toList();

Y aquí es donde llamo a leerTodasLasNotas():

class WidgetListaNotas extends StatefulWidget {


const WidgetListaNotas({
    Key? key,
}) : super(key: key);

  @override
  State createState() => _EstadoWidgetListaNotas();
}

class _EstadoWidgetListaNotas extends State {


  @override
  Widget build(BuildContext context) {
    List notas = BaseDatosNotas.instance.leerTodasLasNotas();

return ListView.builder(
    itemCount: notas.length,
    itemBuilder: (ctx, index) {
      return WidgetTarjetaNota(
        cuerpo: notas[index].cuerpo,
        titulo: notas[index].titulo,
        tiempoAgregado:
            '${notas[index].tiempoAgregado.day}/${notas[index].tiempoAgregado.month}/${notas[index].tiempoAgregado.year}',
        id: notas[index].id,
      );
    });

}
}

Tags:  , , , ,

Answer

  1. Avatar for davy.ai

    El error que estás obteniendo se debe a que readAllNotes() devuelve un Future del tipo List<note>, no un List<note> directamente. Necesitas esperar a que el Future se complete y devuelva el resultado antes de intentar usarlo en tu ListView.builder().

    Puedes hacer esto utilizando la palabra clave await dentro de una función async, de la siguiente manera:

    class _NoteListWidgetState extends State<notelistwidget> {
      List<note> notes = [];
    
      @override
      void initState() {
        super.initState();
        readNotes();
      }
    
      Future<void> readNotes() async {
        final List<note> result = await NotesDataBase.instance.readAllNotes();
        setState(() {
          notes = result;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return ListView.builder(
          itemCount: notes.length,
          itemBuilder: (ctx, index) {
            return NoteTileWidget(
              body: notes[index].body,
              title: notes[index].title,
              timeAdded:
                  ('${notes[index].timeAdded.day}/${notes[index].timeAdded.month}/${notes[index].timeAdded.year}'),
              id: notes[index].id,
            );
          },
        );
      }
    }
    

    En esta implementación actualizada, readNotes() es una función async que espera a que el Future devuelto por readAllNotes() se complete, luego almacena la lista resultante de tipo List<notes> en la variable notes y llama a setState() para desencadenar una reconstrucción del árbol de widgets.

    En el método build(), simplemente podemos utilizar la variable notes directamente sin convertirla a List<note>.

Comments are closed.