Flutter页面传值问题:复用页面处理增编功能时接收数据为空
问题排查与解决方案
问题原因分析
State构造函数传参的错误用法
Flutter中State的构造函数不应直接接收Widget的参数,正确做法是通过State内置的widget属性获取参数。你当前通过State构造函数传递screenData,不仅不符合Flutter生命周期规范,还可能导致数据无法正确同步。空值判断逻辑失效
初始化beneficiaryDataForEdit时使用了fx4uBeneficiaryData ?? BeneficiaryDTOList(),这意味着无论是否传入有效数据,beneficiaryDataForEdit永远不会为null——无数据时会被初始化为一个所有字段都为null的空实例。因此initState里的beneficiaryDataForEdit != null判断永远为真,但打印的toJson()自然是空对象。数据传递可能未正确转换类型
若跳转页面时直接传递原始Map而非BeneficiaryDTOList实例,会导致screenData为null,最终生成空的beneficiaryDataForEdit实例。
修复方案
1. 修正State的初始化逻辑
移除State构造函数的参数传递,改用widget属性获取数据,并优化空值判断逻辑:
class ScreenAddBeneficiary extends StatefulWidget { final BeneficiaryDTOList? screenData; ScreenAddBeneficiary({Key? key, this.screenData}) : super(key: key); @override _ScreenAddBeneficiaryNewState createState() => _ScreenAddBeneficiaryNewState(); } class _ScreenAddBeneficiaryNewState extends State<ScreenAddBeneficiary> { late BeneficiaryDTOList beneficiaryDataForEdit; @override void initState() { super.initState(); // 从widget属性获取数据,无数据时初始化空实例 beneficiaryDataForEdit = widget.screenData ?? BeneficiaryDTOList(); // 改为判断实例字段是否为空,而非实例本身 if (beneficiaryDataForEdit.customerId != null || beneficiaryDataForEdit.beneficiaryType != null || beneficiaryDataForEdit.beneId != null) { Log("Prefetch data>>>${beneficiaryDataForEdit.toJson()}"); } else { Log("未接收到编辑数据"); } } }
2. 确保跳转时传递正确类型的数据
从其他页面跳转时,必须将原始Map转换为BeneficiaryDTOList实例:
// 假设拿到的原始数据是示例中的Map Map<String, dynamic> rawData = { "customerId": "4344654", "beneficiaryType": "FGG", "beneId": "40120", "loginuserid": "R4344654" }; // 转换为BeneficiaryDTOList实例 BeneficiaryDTOList editData = BeneficiaryDTOList.fromJson(rawData); // 跳转并传递数据 Navigator.push( context, MaterialPageRoute( builder: (context) => ScreenAddBeneficiary(screenData: editData), ), );
3. 优化POJO类的空值判断(可选)
给BeneficiaryDTOList添加一个判断是否为空实例的方法,简化后续逻辑:
class BeneficiaryDTOList { String? customerId; String? beneficiaryType; String? beneId; BeneficiaryDTOList({this.customerId, this.beneficiaryType, this.beneId}); BeneficiaryDTOList.fromJson(Map<String, dynamic> json) { customerId = json['customerId']?.toString(); // 确保数字转字符串,匹配字段类型 beneficiaryType = json['beneficiaryType']; beneId = json['beneId']?.toString(); } Map<String, dynamic> toJson() { final Map<String, dynamic> data = {}; data['customerId'] = customerId; data['beneficiaryType'] = beneficiaryType; data['beneId'] = beneId; return data; } // 添加空实例判断方法 bool get isEmpty => customerId == null && beneficiaryType == null && beneId == null; }
之后在initState中可以简化判断:
@override void initState() { super.initState(); beneficiaryDataForEdit = widget.screenData ?? BeneficiaryDTOList(); if (!beneficiaryDataForEdit.isEmpty) { Log("Prefetch data>>>${beneficiaryDataForEdit.toJson()}"); } }
内容的提问来源于stack exchange,提问作者vishnu
相关产品推荐
相关产品推荐

