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

Flutter中带Query Params与Body的HTTP Post请求空值报错求助

排查API调用中的Null Check错误及代码修复

出现Null check operator used on a null value的直接原因是代码中使用!强制解包了null值,同时存在多处变量名不匹配、API调用格式错误等问题,以下是具体排查和修复方案:

1. 表单Key的Null解包风险

按钮代码中:

if (_postKey.currentState!.validate()) {

若_postKey未绑定到表单组件,或表单未完成初始化,currentState会是null,此时!会触发异常。

修复:
替换为安全的空判断:

if (_postKey.currentState?.validate() ?? false) {

2. Controller与Repo的变量/方法名不匹配

Controller代码存在多处拼写错误和不匹配问题:

  • 定义的Repo实例是featureAPostRepo,但调用了未定义的featureAnAdRepo,导致null异常
  • 方法参数ostpId是拼写错误,且Repo方法是featurePost,却调用了不存在的featureAnAd
  • fromFeaturedAds未初始化,调用方法时也会触发null错误

修复后的Controller代码:

class FeaturePostController extends GetxController {
  final featureAPostRepo = FeaturePost();

  Future<dynamic> newFeaturedPost(String postId, String id, int duration, String period) async {
    try {
      final result = await featureAPostRepo.featurePost(duration, period, postId, id);
      Get.back();
      // 确保fromFeaturedAds初始化后再调用,否则注释或补充初始化逻辑
      // await fromFeaturedAds.fetchFeaturedAds();
      print(result);
      return result;
    } catch (e) {
      throw Exception(e);
    }
  }
}

3. Repo中的API调用错误

Repo代码存在多个致命问题:

  • Uri构造错误:用Uri.dataFromString处理HTTP地址完全错误,应使用Uri.https构造带query参数的地址
  • Query参数值错误:'postpId': 'postId'是传入字符串字面量,而非实际变量值
  • Token处理:preferences.getString('token').toString()会把null转为字符串"null",需先判断token是否存在
  • 请求体格式错误:Content-Type为application/json时,body需用jsonEncode转为JSON字符串
  • 未返回请求结果:原代码未return HTTP响应,导致Controller await得到null

修复后的Repo代码:

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

class FeaturePost {
  Future<http.Response> featurePost(int duration, String period, String postId, String id) async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    String? token = preferences.getString('token');
    if (token == null) {
      throw Exception("用户未登录,缺少token");
    }
    final queryParameters = {
      'postId': postId,
      'id': id,
    };
    final uri = Uri.https("url.com", "/api/v1/post", queryParameters);
    
    final response = await http.post(
      uri,
      headers: {
        'Content-Type': 'application/json',
        'x-access-token': token,
      },
      body: jsonEncode({
        "duration": duration,
        "period": period
      }),
    );
    return response;
  }
}

4. 按钮交互中的参数传递错误

按钮代码中调用方法的参数与Controller方法不匹配,且int.parse(durationController.text)存在格式错误风险。

修复后的按钮代码:

GestureDetector(
  onTap: () async {
    setState(() {
      period = dropdownValue.toString();
    });
    if (_postKey.currentState?.validate() ?? false) {
      final duration = int.tryParse(durationController.text);
      if (duration == null) {
        // 提示用户输入有效数字
        return;
      }
      await Get.find<FeaturePostController>().newFeaturedPost(
        widget.postId,
        widget.userId,
        duration,
        period,
      );
    }
  },
  child: const Center(
    child: Text('Make Post Featured'),
  ),
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 03:05:19