You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将从数据库读取的字符串转换为List<String>(Flutter)

解决方法

首先得明确数据库存储的字符串格式,常见两种情况对应不同转换方式:


情况1:字符串是JSON格式的列表(比如 "["苹果","香蕉","橙子"]")

借助Dart的dart:convert库解析:

  1. 先导入依赖库:
import 'dart:convert';
  1. 在获取到数据后,把字符串转成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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 03:40:15