sqlitefluttersimpledialog

Display data from sqlite to simpledialog in flutter


I want to display data from sqlite to SimpleDialog widget

showDialog(
  context: context,
  barrierDismissible: true,
    builder: (BuildContext context) {
      return SimpleDialog(
        title: const Text('Select Category '),
        children: <Widget>[
          dbHelper.getCategories().then((val) {
            for (var item in val) {
              SimpleDialogOption(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: const Text('Food'),
              );
            }
          }),
      ],
    );
});

While doing this I am getting the below error:

type 'Future' is not a subtype of type 'Widget'


Solution

  • You are trying to add SimpleDialogOption widgets to children, but you need to await for the future to complete before adding them.

    type 'Future' is not a subtype of type 'Widget'

    This error should give you a hint: it expects widgets, and you are giving it a future (dbHelper.getCategories().then((val) returns a Future).

    What works is awaiting for your categories before displaying the dialog. For this you can use a FutureBuilder:

    FutureBuilder(
      future: dbHelper.getCategories(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.hasData) {
          showDialog(
            context: context,
            barrierDismissible: true,
            builder: (BuildContext context) {
              return SimpleDialog(
                title: const Text('Select Category '),
                children: [
                  for (var item in snapshot.data) {
                    SimpleDialogOption(
                      onPressed: () { Navigator.pop(context); },
                      child: const Text('Food'),
                    );
                  }
                }