Flutter:从新屏幕返回数据对象

时间:2020-10-08 05:05:28

标签: flutter dart

我想从第二个屏幕返回数据作为对象。在示例中,它们仅作为字符串发送,如果我想将数据作为json对象返回该怎么办。我尝试了: 我使用Json serializable

课程

class LeaveFilterType {
   String shortName;
   String fullName;
   LeaveFilterType({this.shortName, this.fullName});
   factory LeaveFilterType.fromJson(Map<String, dynamic> json) => _$LeaveFilterTypeFromJson(json);
   Map<String, dynamic> toJson() => _$LeaveFilterTypeToJson(this);
}

屏幕1

IconButton(
    onPressed: () async{
    var result = await Navigator.push(context, MaterialPageRoute(builder: (BuildContext context) => FilterView(leaveRequestTypeList: requestTypeList, requestState: RequestState.Supervisor)));
       var finalResult = jsonDecode(result);
       print("result $finalResult");
       FilterLeave filterLeave = FilterLeave.fromJson(finalResult);
       print("result ${filterLeave.toJson()}");
    },
    icon: Image.asset(ImagePath.icFilter, width: AppDimen.value18, color: AppColor.grey,),
)

屏幕2

IconButton(
    splashColor: AppColor.white,
    icon: Icon(Icons.check),
    color: AppColor.white,
    onPressed: () async {
        print(leaveRequest.toJson());
        var filterLeave = FilterLeave(type: leaveRequest, startDate: startDateController.text, endDate :endDateController.text);
         Navigator.of(context).pop("${leaveRequest}");
        }
    ),
 )

总是出错

[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: FormatException: Unexpected character (at character 1)
 Instance of 'LeaveFilterType'

1 个答案:

答案 0 :(得分:0)

据我所知,您只能从Navigator.pop(context, result)返回任何对象

在我的一个项目中,我通过一个对话框进行了以下操作:

DialogResponseObject returnValue = await showDialog<DialogResponseObject>(
  context: context,
  builder: (BuildContext context) =>
      CustomDialog(),
);

在对话框中:

Navigator.pop<DialogResponse>(context,DialogResponseObject(dialogAnswer));

对于您的情况应相同。 实际上,您可以从第一个屏幕输入Navigator.push,而无需序列化。

   FilterLeave result = await Navigator.push<FilterLeave>(context, MaterialPageRoute(builder: (BuildContext context) => FilterView(leaveRequestTypeList: requestTypeList, requestState: RequestState.Supervisor)));


FilterLeave filterLeave = FilterLeave(type: leaveRequest, startDate: startDateController.text, endDate :endDateController.text);
     Navigator.of(context).pop<FilterLeave>(leaveRequest);