You need to enable JavaScript to run this app. Flutter Card组件API数据展示:如何映射snapshot.data并在Stack中渲染?
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Card组件API数据展示:如何映射snapshot.data并在Stack中渲染?

现存代码问题梳理
  • futureNews 未定义:FutureBuilder 依赖的异步数据源没有完成赋值,且如果直接在build方法内给future赋值,会导致每次页面重建都重复发起网络请求
  • 参数传递逻辑混乱:newsCard 方法形参写为size,但实际传入的是snapshot.data对应的News对象,方法内部引用的image是未声明的游离变量,没有和传入的新闻数据建立关联
  • 语法结构错误:Widget树存在多余的闭合括号,无法正常通过编译
  • 空安全适配缺失:Flutter 2.0+ 版本的模型类构造函数未加必填标记,JSON字段没有空值兜底,容易触发运行时崩溃
修正后的实现代码
// State 类初始化,避免重复请求
class _NewsPageState extends State<NewsPage> {
  late Future<News> futureNews;

  @override
  void initState() {
    super.initState();
    // 仅在页面初始化时发起一次网络请求
    futureNews = fetchNews();
  }

  Future<News> fetchNews() async {
    final response = await http.get(Uri.parse('#url'));
    print(response.body);

    if (response.statusCode == 200) {
      return News.fromJson(jsonDecode(response.body));
    } else {
      throw Exception('Failed to load news');
    }
  }

  class News {
    final String title;
    final String description;
    final String image;

    News({
      required this.title,
      required this.description,
      required this.image,
    });

    factory News.fromJson(Map<String, dynamic> json) {
      return News(
        // 增加空值兜底,避免接口返回null崩溃
        title: json['title'] ?? '',
        description: json['description'] ?? '',
        image: json['image'] ?? '',
      );
    }
  }

  Widget _buildPage(BuildContext context, int direction) {
    return SafeArea(
      child: FutureBuilder<News>(
        future: futureNews,
        builder: (context, snapshot) {
          // 加载状态
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          }
          // 错误状态
          if (snapshot.hasError) {
            return Center(child: Text("加载失败:${snapshot.error}"));
          }
          // 成功状态:将解析完成的News对象传给卡片组件
          if (snapshot.hasData) {
            return newsCard(context, snapshot.data!);
          }
          return const SizedBox();
        },
      ),
    );
  }

  Widget newsCard(BuildContext context, News news) {
    Size size = MediaQuery.of(context).size;
    return Stack(
      children: <Widget>[
        // 从传入的News对象取图片地址加载
        Container(
          height: size.height / 2.0,
          width: size.width,
          child: Image.network(
            news.image,
            fit: BoxFit.cover,
            // 图片加载失败兜底
            errorBuilder: (context, error, stackTrace) {
              return const Center(
                child: Icon(Icons.broken_image, size: 48, color: Colors.grey),
              );
            },
          ),
        ),
        // Stack 叠加层:在图片上展示新闻标题、描述
        Positioned(
          bottom: 16,
          left: 16,
          right: 16,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                news.title,
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 8),
              Text(
                news.description,
                style: const TextStyle(color: Colors.white70, fontSize: 14),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ],
          ),
        )
      ],
    );
  }
}
核心调整说明
  • 调整异步数据源的初始化时机:放在initState中完成赋值,避免高频的无效网络请求
  • 理顺参数传递逻辑:newsCard 方法分别接收context(用于获取屏幕尺寸)和News对象(用于读取接口返回的字段值),不再混淆参数类型
  • 补全FutureBuilder的状态判断逻辑,区分加载中、加载失败、加载成功三种场景,避免状态判断不全导致的异常
  • 给JSON解析、图片加载环节增加空值和错误兜底,提升页面稳定性
  • 基于Stack组件的特性,实现新闻图片作为底层、文本信息作为上层叠加层的常见卡片展示效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.10 20:36:07