如何将从数据库读取的字符串转换为List<String>(Flutter)
解决方法
首先得明确数据库存储的字符串格式,常见两种情况对应不同转换方式:
情况1:字符串是JSON格式的列表(比如 "["苹果","香蕉","橙子"]")
借助Dart的dart:convert库解析:
- 先导入依赖库:
import 'dart:convert';
- 在获取到数据后,把字符串转成
List<String>:
data: (data) { List<String> nameList = []; try { // 解析JSON格式的字符串为动态列表 List<dynamic> tempList = jsonDecode(data.name); // 转换为String类型列表 nameList = tempList.cast<String>(); } catch (e) { // 解析失败时给默认空列表,避免崩溃 nameList = []; } return Scaffold( body: ListView( children: [ for (int i = 0; i < nameList.length; i++) RadioListTile( title: Text(nameList[i]), value: i, groupValue: _selectedRadio, onChanged: (value) { _selectedRadio = value as int?; setState(() {}); // 必须调用setState更新UI选中状态 }, ), ], ), ); },
情况2:字符串是分隔符拼接的(比如 "苹果,香蕉,橙子",分隔符为逗号)
直接用split方法分割字符串:
data: (data) { // 按逗号分割字符串得到列表 List<String> nameList = data.name.split(','); // 可选:去除每个元素的首尾空格 nameList = nameList.map((item) => item.trim()).toList(); return Scaffold( body: ListView( children: [ for (int i = 0; i < nameList.length; i++) RadioListTile( title: Text(nameList[i]), value: i, groupValue: _selectedRadio, onChanged: (value) { _selectedRadio = value as int?; setState(() {}); // 调用setState触发UI更新 }, ), ], ), ); },
关键注意点
- 务必添加异常处理(比如JSON解析失败、分隔符格式异常),防止程序崩溃
- 修改
_selectedRadio后必须调用setState(() {}),否则Radio的选中状态不会同步到UI
内容的提问来源于stack exchange,提问作者Jabu
相关产品推荐
相关产品推荐

