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

Flutter中如何用ListView.builder展示JSON城市数据并保存选中ID

在Flutter中用ListView.builder展示城市列表并保存选中的CTID

1. 定义城市数据模型类

先创建一个City类,用来映射JSON中的城市数据,让数据操作更直观:

class City {
  final String ctid;
  final String name;
  final String status;

  City({
    required this.ctid,
    required this.name,
    required this.status,
  });

  // 从JSON对象转成City实例的工厂方法
  factory City.fromJson(Map<String, dynamic> json) {
    return City(
      ctid: json['CTID'],
      name: json['City'],
      status: json['Status'],
    );
  }
}

2. 解析JSON响应

把你拿到的JSON数据解析成List<City>类型的列表:

// 假设jsonResponse是你获取到的JSON字符串
Map<String, dynamic> responseData = jsonDecode(jsonResponse);
List<City> cityList = (responseData['cities'] as List)
    .map((cityJson) => City.fromJson(cityJson))
    .toList();

3. 构建ListView并处理点击事件

在StatefulWidget中使用ListView.builder渲染列表,同时在点击时保存选中城市的CTID:

// 声明变量存储选中的CTID
String? selectedCtid;

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(title: const Text('城市列表')),
    body: ListView.builder(
      itemCount: cityList.length,
      itemBuilder: (context, index) {
        final currentCity = cityList[index];
        return ListTile(
          title: Text(currentCity.name),
          // 点击城市项时保存CTID
          onTap: () {
            setState(() {
              selectedCtid = currentCity.ctid;
            });
            // 可添加其他逻辑,比如打印选中的ID
            print('选中的城市CTID:$selectedCtid');
          },
          // 可选:给选中的城市添加选中标记
          trailing: selectedCtid == currentCity.ctid
              ? const Icon(Icons.check, color: Colors.blue)
              : null,
        );
      },
    ),
  );
}

额外提示

  • 如果数据来自网络请求,推荐用FutureBuilder处理异步加载,避免在build方法中直接做解析操作。
  • 若使用Provider、Riverpod等状态管理工具,可替换setState为对应状态更新方式,实现跨组件状态共享。

内容的提问来源于stack exchange,提问作者Ram Gupta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 22:36:14