颤振错误:颤振/lib/ui/ui_dart_state.cc(198)] 未处理的异常:类型 'String' 不是类型 'int' 的子类型 'index'



型号:

class ModelClass {
String? userId;
String? id;
String? title;
String? body;
ModelClass({
this.userId,
this.id,
this.title,
this.body,
});
Map<String, dynamic> toJson() {
return {'userId': userId, 'id': id, 'title': title, 'body': body};
}
factory ModelClass.fromJson(Map<String, dynamic> data) {
final userId = data['userId'];
final id = data['id'];
final title = data['title'];
final body = data['body'];
return ModelClass(id: id, userId: userId, title: title, body: body);
}
}

回购:

class GetPostProvider with ChangeNotifier {
bool isLoading = false;
List<ModelClass> modelclass = [];
getMyData() async {
isLoading = true;
modelclass = await getAllPost();
isLoading = false;
notifyListeners();
}
Future<List<ModelClass>> getAllPost() async {
final response =
await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
List<ModelClass> mylist = [];
try {
if (response.statusCode == 200) {
final jsonDecode = await json.decode(response.body);
for (var i in jsonDecode['data']) {
ModelClass _model = ModelClass.fromJson(i);
mylist.add(_model);
}
return mylist;
} else {
return mylist;
}
} catch (e) {
throw e.toString();
}
}
}

UI:

class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
void initState() {
// TODO: implement initState
final provider = Provider.of<GetPostProvider>(context, listen: false);
provider.getMyData();
super.initState();
}
@override
Widget build(BuildContext context) {
final provider = Provider.of<GetPostProvider>(context);
return Scaffold(
appBar: AppBar(
title: const Text('User Id'),
),
body: ListView.builder(
itemCount: provider.modelclass.length,
itemBuilder: ((context, index) {
return ListTile(
title: Text("${provider.modelclass[index].body}"),
);
})));
}
}

错误:

[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'
E/flutter (13226): #0      GetPostProvider.getAllPost (package:apiflutter/provider/postProvider.dart:51:7)
E/flutter (13226): <asynchronous suspension>
E/flutter (13226): #1      GetPostProvider.getMyData (package:apiflutter/provider/postProvider.dart:26:18)
E/flutter (13226): <asynchronous suspension>
E/flutter (13226):

请帮我

正如我所看到的,从JSON中,JSON结构中没有字段"data"。你只需要使用:

final jsonDecode=await json.decode(response.body);
for (var i in jsonDecode){
ModelClass _model=ModelClass.fromJson(i);
mylist.add(_model);
}

在GetPostProvider类中。

jsonDecode['data']替换为jsonDecode。因为作为响应,您不会收到Map<字符串,动态>具有键"data",但List<映射<字符串,动态>(如评论中的@julemand101动议(。

相关内容

  • 没有找到相关文章

最新更新