1

Sure this is something fundamental, but I'm trying to put the results of a database query into a DataTable widget with the below:

class ADataTable extends StatelessWidget {

  ADataTable({Key? key}) : super(key: key);

  var resultSet = generateRows();

  @override
  Widget build(BuildContext context) {
    return DataTable(
      columns: setHeader(['Date','In Temp','Out Temp']),
      rows: resultSet
    );
  }
}

The signature of generateRows is:

Future<List<DataRow>> generateRows() async

However, as expected I'm getting the error:

The argument type 'Future<List<DataRow>>' can't be assigned to the parameter type 'List<DataRow>'.

I've tried various ways to "cast away" the Future but it seems I just keep propagating a Future no matter how I try, so must be missing something fundamental! Appreciate the help!

jparanich
  • 8,372
  • 4
  • 26
  • 34
  • 1
    Does this answer your question? [What is a Future and how do I use it?](https://stackoverflow.com/questions/63017280/what-is-a-future-and-how-do-i-use-it) – nvoigt Nov 24 '21 at 22:31
  • It helps some understanding, but even with "List resultsSet = await generateRows();" I can't use await directly in a class body, so if I wrap it in an async function I'm still in the same issue, hence my comment on propagating the Future. =\ – jparanich Nov 24 '21 at 22:46
  • Have you tried using `FutureBuilder`? You may display some loading indicator while the future is ongoing, then display the `DataTable` when the future's result comes. – rickimaru Nov 24 '21 at 22:51

1 Answers1

1

You created a StatelessWidget, yet the first real line of code is your widget holding state. That won't work.

Create a StatefulWidget, create a State class for it, then in your state class, create a Future<> variable. You can set this variable in the initState method. Then in the build method, you can use this variable and a FutureBuilder widget to make your widget react to the fact that data may come in after it started to show, since it's async.

See What is a Future and how do I use it? for a more detailed explanation why and a full example.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • Thanks, this helped steer me properly, in conjunction with the article here; https://stackoverflow.com/questions/51983011/when-should-i-use-a-futurebuilder – jparanich Nov 26 '21 at 20:05