gpt4 book ai didi

dart - 'String' 不是 'int' flutter 的子类型

转载 作者:IT王子 更新时间:2023-10-29 06:34:23 27 4
gpt4 key购买 nike

这是我的第一个 flutter JSON 示例,我尝试从 json 链接获取数据并将标题显示为 ListView

我用了这个code写我的一些变化.. 在链接中他有 results array 在我的我没有所以我离开了 data = resBody[""];是空的吗?

另外,我在 flutter 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();
}
}

最佳答案

您的 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!";
}

关于dart - 'String' 不是 'int' flutter 的子类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54179265/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com