API请求无指定字段时的变量处理及Dart类型错误解决
问题描述
在Flutter项目中通过HTTP请求调用API,需求是当响应的situation字段值为0时显示提示消息,该逻辑正常运行;但当响应中不存在situation字段时,代码抛出如下错误:
Another exception was thrown: TypeError: null: type 'Null' is not a subtype of type 'String'
导致代码无法执行,尽管已考虑到situation可能不存在的情况。相关Dart代码如下:
import 'dart:async'; import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:flutter/material.dart'; class GamePage extends StatefulWidget { String time = ""; GamePage({ super.key, //required this.mailc, required this.mdp // required GlobalKey<FormState> formKey, required this.mail, required this.password, //required this.controllermotdepasse }); final String mail; final String password; @override State<GamePage> createState() => _GamePageState(); } class _GamePageState extends State<GamePage> { Future<void> container() async { var url = Uri.parse('https://konamicash.com/vfetch_app'); var response = await http.post(url, headers: { "Accept": "application/json", "Access-Control-Allow-Origin": "*" }, body: { "adresse_mail": widget.mail, }); if (response.statusCode == 200) { var reponse = jsonDecode(response.body); String? situation = reponse['situation']; if (situation == 0) { print('no data avalaible'); ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('no game'), ), ); } else {// here is where situation is supposed to not exist and where i get this message //Another exception was thrown: TypeError: null: type 'Null' is not a subtype of type 'String' var image_team = reponse['image_team']; Navigator.push( context, PageRouteBuilder( pageBuilder: (context, animation, secondaryAnimation) => team( mail: widget.mail, password: widget.password, team: image_team), // TestVfetch(mail: widget.mail, password: widget.password), transitionsBuilder: (context, animation, secondaryAnimation, child) { animation = CurvedAnimation(parent: animation, curve: Curves.ease); return FadeTransition( opacity: animation, child: child, ); }), ); } print(reponse); } } }
问题分析与修复
错误原因
- 类型不匹配:你将
situation声明为String?类型,但API返回的situation是数字0(非字符串"0");当响应无situation字段时,reponse['situation']返回null,后续逻辑触发类型转换错误。 - 判断逻辑无效:
situation == 0是字符串与数字比较,即使situation为"0"也不会匹配;进入else分支后,若image_team为null,传递给team页面时如果参数要求非空,会再次触发类型错误。
修复方案
1. 修正situation的类型与判断逻辑
将situation改为int?类型,先判断字段是否存在再做值比较:
2. 处理image_team的空值情况
确保image_team非空时再跳转,避免传递空值导致的错误。
修复后的代码示例:
Future<void> container() async { var url = Uri.parse('https://konamicash.com/vfetch_app'); var response = await http.post(url, headers: { "Accept": "application/json", "Access-Control-Allow-Origin": "*" }, body: { "adresse_mail": widget.mail, }); if (response.statusCode == 200) { var reponse = jsonDecode(response.body); // 适配API返回的数字类型,声明为可空int int? situation = reponse['situation'] as int?; // 先判断字段存在且值为0 if (situation != null && situation == 0) { print('no data available'); ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('no game'), ), ); } else { var image_team = reponse['image_team']; // 确保image_team非空再跳转 if (image_team != null) { Navigator.push( context, PageRouteBuilder( pageBuilder: (context, animation, secondaryAnimation) => team( mail: widget.mail, password: widget.password, team: image_team), transitionsBuilder: (context, animation, secondaryAnimation, child) { animation = CurvedAnimation(parent: animation, curve: Curves.ease); return FadeTransition( opacity: animation, child: child, ); }), ); } else { // 可选:空值时的提示处理 ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('缺少团队信息'), ), ); } } print(reponse); } }
额外建议
- 推荐使用
json_serializable生成模型类解析API响应,彻底避免手动解析的类型错误; - 对所有从响应中获取的字段都做空值校验,提升代码健壮性。
内容的提问来源于stack exchange,提问作者Deenan Djigbenou
相关产品推荐
相关产品推荐

