Search code examples
flutterdropdownsqflite

Flutter : Recover sqlite data in combobox


I want to recover data from my table and put them in my dropdown. I get an error message : _TypeError (type 'Future' is not a subtype of type 'List') Thank you for your help

readData(table) async {
  var connection = await db;
  return await connection.query('SELECT nom_A FROM tab_A');
}


class DropdownMenuA extends StatefulWidget {
  const DropdownMenuA({super.key});
//Modif

  @override
  State<DropdownMenuA> createState() => _DropdownMenuAState();
}

class _DropdownMenuAState extends State<DropdownMenuA> {
  //String dropdownValueA = list1.first;
  List<String> listA = readData(Tab_A);

  @override
  Widget build(BuildContext context) {
    return DropdownMenu<String>(
      initialSelection: listA.first,
      onSelected: (String? value) {
        // This is called when the user selects an item.
        setState(() {
          //dropdownValueA = value!;
        });
      },
      dropdownMenuEntries: listA.map<DropdownMenuEntry<String>>((String value) {
        return DropdownMenuEntry<String>(value: value, label: value);
      }).toList(),
    );
  }
}


Solution

  • Put await keyword for the Future call. Like:

    List<String> listA = await readData(Tab_A);
    
    

    In order to use await keyword you must also use the async keyword as well like:

    Future<void> fetchData() async {
        List<String> data = await readData(Tab_A);
        setState(() {
          listA = data;
        });
      }
    

    And call this fetchData() function inside initState() function like:

     @override
      void initState() {
        super.initState();
        fetchData();
      }
    

    Final code looks like:

    class _DropdownMenuAState extends State<DropdownMenuA> {
      List<String> listA = [];
    
      @override
      void initState() {
        super.initState();
        fetchData();
      }
    
      Future<void> fetchData() async {
        List<String> data = await readData(Tab_A);
        setState(() {
          listA = data;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return DropdownMenu<String>(
          initialSelection: listA.isNotEmpty ? listA.first : null,
          onSelected: (String? value) {
          
            setState(() {
      
            });
          },
          dropdownMenuEntries: listA.map<DropdownMenuEntry<String>>((String value) {
            return DropdownMenuEntry<String>(value: value, label: value);
          }).toList(),
        );
      }
    }
    

    Kindly, let me know if it works.