颤振错误:类型“int”不是类型转换中“String”类型的子类型
Posted
技术标签:
【中文标题】颤振错误:类型“int”不是类型转换中“String”类型的子类型【英文标题】:Flutter error: type 'int' is not a subtype of type 'String' in type cast 【发布时间】:2019-08-14 17:25:12 【问题描述】:我正在尝试使用 Flutter 应用从 REST API 获取数据。我正在json_serializable way
中构建模型类。下面是我的代码。
main.dart
import 'package:flutter/material.dart';
import 'dart:convert' as convert;
import 'package:http/http.dart' as http;
import './category.dart';
void main()
runApp(MyApp());
class MyApp extends StatefulWidget
@override
State<StatefulWidget> createState()
// TODO: implement createState
return HttpTestState();
class HttpTestState extends State<MyApp>
@override
Widget build(BuildContext context)
//bookFind();
productFind();
return MaterialApp(
title: 'Flutter layout demo',
home: Scaffold(
body: Scaffold(appBar: AppBar(title: Text("HTTP Test"),),
body: Container(child: Text("data"),),)
),
);
productFind() async
var url = "http://10.0.2.2:8080/xxx/rest/productCategory/getAllProductCategories";
// Await the http get response, then decode the json-formatted responce.
var response = await http.get(Uri.encodeFull(url), headers: "Accept": "application/json");
if (response.statusCode == 200)
print("Response Body: "+response.body);
List userMap = convert.jsonDecode(response.body);
Category ProductCategories = new Category.fromJson(userMap[0]);
else
print("Request failed with status: $response.statusCode.");
category.dart(模型类)
import 'package:json_annotation/json_annotation.dart';
part 'category.g.dart';
@JsonSerializable()
class Category
int idproductCategory;
String categoryName;
String imageURL;
String deleteTimestamp;
String dateCreated;
String lastUpdated;
Category(this.idproductCategory, this.categoryName, this.imageURL, this.deleteTimestamp, this.dateCreated, this.lastUpdated);
factory Category.fromJson(Map<String, dynamic> json) => _$CategoryFromJson(json);
Map<String, dynamic> toJson() => _$CategoryToJson(this);
category.g.dart(json_serializable
生成的类)
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'category.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Category _$CategoryFromJson(Map<String, dynamic> json)
return Category(
json['idproductCategory'] as int,
json['categoryName'] as String,
json['imageURL'] as String,
json['deleteTimestamp'] as String,
json['dateCreated'] as String,
json['lastUpdated'] as String);
Map<String, dynamic> _$CategoryToJson(Category instance) => <String, dynamic>
'idproductCategory': instance.idproductCategory,
'categoryName': instance.categoryName,
'imageURL': instance.imageURL,
'deleteTimestamp': instance.deleteTimestamp,
'dateCreated': instance.dateCreated,
'lastUpdated': instance.lastUpdated
;
对给定 URL 的 JSON 响应应如下所示。
[
"idproductCategory": 1,
"categoryName": "Fruits",
"imageURL": "https://images.unsplash.com/photo-1512621776951-a57141f2eefd?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
"deleteTimestamp": null,
"dateCreated": 1550056389000,
"lastUpdated": 1550056389000
,
"idproductCategory": 2,
"categoryName": "Vegetables",
"imageURL": "https://images.unsplash.com/photo-1522184216316-3c25379f9760?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
"deleteTimestamp": null,
"dateCreated": 1550056389000,
"lastUpdated": 1550056389000
]
但是,当我运行我的代码时,出现以下错误。
E/flutter ( 6448): [ERROR:flutter/shell/common/shell.cc(178)] Dart Error: Unhandled exception:
E/flutter ( 6448): type 'int' is not a subtype of type 'String' in type cast
E/flutter ( 6448): #0 _$CategoryFromJson
E/flutter ( 6448): #1 new Category.fromJson
E/flutter ( 6448): #2 HttpTestState.productFind
E/flutter ( 6448): <asynchronous suspension>
E/flutter ( 6448): #3 HttpTestState.build
E/flutter ( 6448): #4 StatefulElement.build
E/flutter ( 6448): #5 ComponentElement.performRebuild
E/flutter ( 6448): #6 Element.rebuild
E/flutter ( 6448): #7 BuildOwner.buildScope
E/flutter ( 6448): #8 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame
E/flutter ( 6448): #9 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback
E/flutter ( 6448): #10 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback
E/flutter ( 6448): #11 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame
E/flutter ( 6448): #12 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.scheduleWarmUpFrame.<anonymous closure>
E/flutter ( 6448): #13 Timer._createTimer.<anonymous closure> (dart:async/runtime/libtimer_patch.dart:21:15)
E/flutter ( 6448): #14 _Timer._runTimers (dart:isolate/runtime/libtimer_impl.dart:382:19)
E/flutter ( 6448): #15 _Timer._handleMessage (dart:isolate/runtime/libtimer_impl.dart:416:5)
E/flutter ( 6448): #16 _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
这是为什么?
【问题讨论】:
【参考方案1】:您的 dateCreated 具有 int 时间戳,但您的类别模型具有字符串数据类型。将类别模型中的String dateCreated;
和String lastUpdated;
分别更改为int dateCreated
和int lastUpdated
【讨论】:
太棒了,是的,确实有效。然而,它们是TimeStamps
,更优选的是SQLTimeStamps
。你知道如何在 Flutter 中处理这种类型吗?
尝试将int
更改为DateTime
看看是否有效。如果没有,我认为应该有一种解决方法,方法是创建自己的fromJson
或在模型中创建一个方法来将 int 转换为 dateTime。让我知道它是否不起作用。您可能需要为其创建一个不同的问题。
我认为无法自动转换。您必须在int
中获取它并转换为DateTime
好的。我会检查并回复您。
我创建了一个问题来展示如何进行转换***.com/questions/55328064/…【参考方案2】:
我发现的最佳解决方法
int pageCount = int.parse(snapshot.data.data['totalPg'].toString());
【讨论】:
【参考方案3】:最好的方法是使用这个包中的注解。例如
@JsonSerializable(explicitToJson: true)
class Artist
String name;
String listeners;
@JsonKey(defaultValue: '')
String mid;
将为mid
字段生成带有空检查的代码
Artist _$ArtistFromJson(Map<String, dynamic> json)
return Artist(
name: json['name'] as String,
listeners: json['listeners'] as String,
mid: json['mid'] as String? ?? '',
【讨论】:
以上是关于颤振错误:类型“int”不是类型转换中“String”类型的子类型的主要内容,如果未能解决你的问题,请参考以下文章
在骇客新闻中的颤振小部件测试中,类型“int”不是“String”类型的子类型
未处理的异常:'String' 类型不是'index' 的'int' 类型的子类型问题 Dart 和颤振
颤振错误:需要一个“String”类型的值,但得到一个“int”类型的值
我在尝试登录或注册时收到错误消息“错误类型‘AuthResult’不是类型转换中‘FirebaseUser’类型的子类型”