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

Flutter调用非列表REST API触发Null check operator空值错误求助

解决「Null check operator used on a null value」错误

问题根源

  • 页面首次渲染时API请求未完成,dataFromAPI仍为null,但build方法直接用!强制解包null值,触发错误。
  • dispose方法中错误调用_getData(),组件销毁时发起网络请求无意义,还可能引发内存泄漏。
  • totFac是double类型,用as String强制类型转换会报错,正确方式是调用toString()。

修复步骤

  1. 添加加载状态判断:利用已有的_isLoaded变量,数据加载完成前显示加载组件,避免直接访问null数据。
  2. 移除dispose中的API请求:删除dispose里的_getData()调用。
  3. 修正数值转字符串方式:将dataFromAPI!.vtaFacG.totFac as String改为dataFromAPI!.vtaFacG.totFac.toString()。

修改后的完整页面代码

import 'dart:convert';
import 'dart:developer';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:velneoapp/api/modelos/api_model_detalles_de_albaranes.dart';

class DetalleDeAlbaranView extends StatefulWidget {
  const DetalleDeAlbaranView({super.key, required this.index});
  final int index;
  @override
  State<DetalleDeAlbaranView> createState() => _DetalleDeAlbaranViewState();
}

class _DetalleDeAlbaranViewState extends State<DetalleDeAlbaranView> {
  @override
  void initState() {
    super.initState();
    _getData();
  }

  bool _isLoaded = true;
  AlbaranesDeVentaDetalle? dataFromAPI;

  _getData() async {
    try {
      String url =
          "https://demoapi.velneo.com/verp-api/vERP_2_dat_dat/v1/vta_fac_g/3?api_key=api123";
      http.Response res = await http.get(Uri.parse(url));
      log("${res.body}");
      if (res.statusCode == 200) {
        log("hecho");
        dataFromAPI = AlbaranesDeVentaDetalle.fromJson(json.decode(res.body));
        setState(() {
          _isLoaded = false;
        });
      } else {
        throw ("Error during connection");
      }
    } catch (e) {
      log("Error");
      log(e.toString());
      setState(() {
        _isLoaded = false; // 请求失败也结束加载状态,可添加错误提示
      });
    }
  }

  @override
  void dispose() {
    super.dispose();
    // 移除多余的_getData()调用
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Detalle de albaranes"),
      ),
      body: Padding(
        padding: EdgeInsets.all(8.0),
        child: _isLoaded 
            ? const Center(child: CircularProgressIndicator()) // 加载中显示进度圈
            : dataFromAPI == null 
                ? const Center(child: Text("数据加载失败")) // 请求失败提示
                : Column(
                    children: [
                      Row(
                        children: [
                          const Text("TOTFAC: "),
                          Text(dataFromAPI!.vtaFacG.totFac.toString()),
                        ],
                      ),
                      Row(
                        children: [
                          const Text("FCH: "),
                          Text("${dataFromAPI!.vtaFacG.fch}"),
                        ],
                      ),
                      Row(
                        children: [
                          const Text("NUM_FAC: "),
                          Text(dataFromAPI!.vtaFacG.numFac),
                        ],
                      ),
                    ],
                  ),
      ),
    );
  }
}

额外优化建议

  • 为VtaFacG.fromJson添加null安全处理,避免API返回字段缺失导致的错误:
    factory VtaFacG.fromJson(Map<String, dynamic> json) => VtaFacG(
          fch: DateTime.parse(json["fch"] ?? DateTime.now().toIso8601String()),
          numFac: json["num_fac"] ?? "",
          clt: json["clt"] ?? 0,
          totFac: (json["tot_fac"] ?? 0.0).toDouble(),
        );
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 01:28:05