如何在Flutter中用本地数据库数据填充DropdownSearch组件
解决本地数据库数据填充DropdownSearch的问题
1. 修复数据获取方法的返回值
你的getList()方法没有返回获取到的列表,同时应明确返回类型以保证类型安全,修正后代码如下:
Future<List<PointOfSale>> getList() async { final db = await getDatabase(); final res = await db.rawQuery("SELECT * FROM tb_point_of_Sale"); return res.isNotEmpty ? res.map((c) => PointOfSale.fromJson(c)).toList() : []; }
2. 用FutureBuilder处理异步数据
数据库查询是异步操作,不能直接将Future对象赋值给DropdownSearch的items参数,需要通过FutureBuilder监听异步状态,待数据加载完成后再渲染组件。同时DropdownSearch的泛型需与数据类型匹配,并指定对象转显示文本的规则:
body: Column( children: [ FutureBuilder<List<PointOfSale>>( future: PointOfSaleDao.db.getList(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const CircularProgressIndicator(); } else if (snapshot.hasError) { return Text('加载失败: ${snapshot.error}'); } else if (!snapshot.hasData || snapshot.data!.isEmpty) { return const Text('暂无销售点数据'); } else { return DropdownSearch<PointOfSale>( mode: Mode.MENU, items: snapshot.data!, showSearchBox: true, label: "Menu mode", hint: "point of sale in menu mode", // 替换为PointOfSale类中你需要显示的字段,比如name、location等 itemAsString: (PointOfSale pos) => pos.name, onChanged: (value) { if (value != null) { // 处理选中值的逻辑 print('选中销售点: ${value.name}'); } }, ); } }, ), ], ),
关键注意点
- 异步数据必须通过
FutureBuilder处理,避免直接传递Future给组件参数 - 保持泛型类型一致,
DropdownSearch的泛型要和数据库返回的列表元素类型匹配 - 通过
itemAsString指定对象转显示文本的规则,确保下拉框能正确展示内容
内容的提问来源于stack exchange,提问作者Rodriguez Diakiese
相关产品推荐
相关产品推荐

