这是我第一个抖动的JSON示例,我尝试从json链接中获取数据并将标题显示为列表视图
我用这个code来写我的代码,做了一些更改..在链接中他拥有我没有的results
数组,所以我离开了data = resBody[" "];
那是空的吗?
另外,我在HTTP请求抖动中也遇到了这个错误,实际上并没有做什么
有什么帮助吗?
Dart Error: Unhandled exception:
type 'String' is not a subtype of type 'int' of 'index'
这是我的代码
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
void main() {
runApp(MaterialApp(
home: ToDo(),
));
}
class ToDo extends StatefulWidget {
@override
ToDoState createState() => ToDoState();
}
class ToDoState extends State<ToDo> {
final String url = "https://jsonplaceholder.typicode.com/todos";
List data;
Future<String> getTitle() async {
var res = await http
.get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
setState(() {
var resBody = json.decode(res.body);
data = resBody[" "];
});
return "Success!";
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Title List"),
backgroundColor: Colors.amber,
),
body: ListView.builder(
itemCount: data == null ? 0 : data.length,
itemBuilder: (BuildContext context, int index) {
return new Container(
child: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Card(
child: Container(
padding: EdgeInsets.all(15.0),
child: Row(
children: <Widget>[
Text("Title: "),
Text(data[index]["title"],
style: TextStyle(
fontSize: 18.0, color: Colors.black87)),
],
)),
),
],
),
),
);
},
),
);
}
@override
void initState() {
super.initState();
this.getTitle();
}
}
答案 0 :(得分:0)
您的getTitle
方法需要更改为以下内容:
Future<String> getTitle() async {
var res = await http
.get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
setState(() {
var resBody = json.decode(res.body);
data = resBody; //This line changed from data = resBody[" "];
});
return "Success!";
}
答案 1 :(得分:-1)
当我忘记在请求头中添加接受类型时出现此错误