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

如何将list.dart中的List数据在main.dart的Text组件中使用?

在Flutter中展示列表中的place数据到Text组件

步骤1:导入list.dart文件

在main.dart的顶部添加导入语句,确保能访问hotelList:

import 'list.dart';

场景1:垂直展示所有place项(推荐长列表)

使用ListView.builder高效渲染列表中的每个元素:

child: ListView.builder(
  itemCount: hotelList.length, // 列表项总数
  itemBuilder: (BuildContext context, int index) {
    final hotel = hotelList[index];
    return Row(
      children: [
        Text(
          // 读取place字段,为空时显示默认文本
          hotel['place'] ?? '未知地点',
          style: TextStyle(fontSize: 16),
        ),
      ],
    );
  },
),

场景2:水平展示所有place项(一行内滚动)

如果需要在一行中展示所有place并支持横向滚动,使用SingleChildScrollView配合Row:

child: SingleChildScrollView(
  scrollDirection: Axis.horizontal, // 设置横向滚动
  child: Row(
    children: hotelList.map((hotel) {
      return Padding(
        padding: const EdgeInsets.symmetric(horizontal: 10.0),
        child: Text(
          hotel['place'] ?? '未知地点',
          style: TextStyle(fontSize: 16),
        ),
      );
    }).toList(),
  ),
),

场景3:展示单个指定项

如果只需要展示列表中某一个特定项(比如第一个):

child: Row(
  children: [
    Text(
      hotelList[0]['place'] ?? '未知地点',
    ),
  ],
),

说明:

  • 通过hotelList[index]['place']可直接访问列表对应索引元素的place字段
  • 添加?? '默认文本'是为了处理字段缺失或为null的情况,避免运行时错误

内容的提问来源于stack exchange,提问作者Rafiqul Islam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 10:20:36