Home > Software engineering >  How to populate DropdownSearch flutter with local database in flutter
How to populate DropdownSearch flutter with local database in flutter

Time:12-19

I want to populate my DropdownSearch with fetching data from local database. plese help me.

Future<dynamic> getList() async {
    final db = await getDatabase();
    final res = await db.rawQuery("SELECT * FROM tb_point_of_Sale");

    List<dynamic> list =
        res.isNotEmpty ? res.map((c) => PointOfSale.fromJson(c)).toList() : [];
  }
body: Column(
        children: [
          DropdownSearch<String>(
            mode: Mode.MENU,
            items: PointOfSaleDao.db.getList(),
            showSearchBox: true,
            label: "Menu mode",
            hint: "point of sale in menu mode",
            onChanged: (value){
               
            }
          ),
        ],
      ),

CodePudding user response:

Here is an example of how you can do it:

Future<List<String>> getList() async {
  final db = await getDatabase();
  final res = await db.rawQuery("SELECT * FROM tb_point_of_Sale");

  List<String> list = res.isNotEmpty ? res.map((c) => c['name']).toList() : [];
  return list;
}



body: Column(
  children: [
    DropdownSearch<String>(
      mode: Mode.MENU,
      items: getList(),
      showSearchBox: true,
      label: "Menu mode",
      hint: "point of sale in menu mode",
      onChanged: (value) {

      }
    ),
  ],
),

In this example, the getList() function is an asynchronous function that fetches the data from the local database and returns a list of strings (assuming that the name column in the tb_point_of_Sale table contains the names you want to display in the DropdownSearch widget).

The getList() function returns a Future<List>, so you need to make sure that the DropdownSearch widget is rebuilt whenever the data changes by using a FutureBuilder widget.

CodePudding user response:

As getList returns a Future, use a FutureBuilder to draw the widget for each state the Future can be, whether it's still loading or finished fetching the data.

In case you are using the dropdown search package, there seems to be a field for that named asyncItems on it you might want to look into.

  • Related