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

Flutter解析网络JSON数据时遇FutureBuilder builder非空返回错误

问题解决:FutureBuilder Builder回调非空安全错误

错误原因

你的FutureBuilder的builder函数中,条件分支没有覆盖所有可能的快照状态,编译器判定存在路径会返回null,但builder要求必须返回非空的Widget类型,因此触发报错。

修复方案

  1. 完善条件分支逻辑:确保所有代码路径都返回Widget,通过调整判断顺序,最后用else兜底处理加载状态;
  2. 修正加载状态UI:原代码中!snapshot.hasData时返回"Data Ok"不符合逻辑,替换为标准加载指示器;
  3. 确保JSON解析类型安全:jsonDecode返回动态类型,显式转换为List<String>避免运行时类型错误。

修改后的完整代码

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Mydata(),
    );
  }
}

class Mydata extends StatefulWidget {
  const Mydata({super.key});

  @override
  State<Mydata> createState() => _MydataState();
}

class _MydataState extends State<Mydata> {
  Future<List<String>> ebdetails() async {
    var response = await http.get(Uri.parse('http://117.247.181.113:8000/eb/1'));
    // 显式转换为List<String>,保证类型安全
    final List<dynamic> rawData = jsonDecode(response.body);
    return rawData.cast<String>();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        elevation: 0,
        centerTitle: true,
        title: const Text(
          'Json Datas',
          style: TextStyle(
            color: Colors.black,
          ),
        ),
        backgroundColor: Colors.white,
      ),
      body: Center(
        child: FutureBuilder<List<String>>(
          // 指定泛型类型,提升类型检查严谨性
          builder: (context, snapshot) {
            // 优先处理错误状态
            if (snapshot.hasError) {
              return const Center(
                child: Text('数据加载错误'),
              );
            }
            // 处理数据已加载完成状态
            if (snapshot.hasData) {
              return ListView.builder(
                itemCount: snapshot.data!.length,
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text(snapshot.data![index]),
                  );
                },
              );
            }
            // 兜底处理加载中状态
            return const Center(
              child: CircularProgressIndicator(),
            );
          },
          future: ebdetails(),
        ),
      ),
    );
  }
}

关键修改点说明

  • 调整builder内条件顺序,先处理错误、再处理已加载数据,最后默认返回加载指示器,确保无路径返回null;
  • 给FutureBuilder指定泛型List<String>,让编译器提前做类型校验;
  • 优化JSON解析逻辑,显式转换类型避免运行时类型不匹配问题;
  • 替换加载状态文本为标准加载组件,符合用户对加载状态的预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 01:20:41