“字符串”不是“int”颤振的子类型

Tab*_*san 6 dart flutter

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

我用这段代码写了我的一些更改..在他有results我的数组的链接中我没有所以我data = resBody[" "]; 留空是对的吗?

另外,我在 flutter HTTP 请求中遇到了这个错误,但我真的不知道该怎么做

有什么帮助吗?

Dart Error: Unhandled exception:
 type 'String' is not a subtype of type 'int' of 'index'
Run Code Online (Sandbox Code Playgroud)

这是我的代码

 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();
  }
}
Run Code Online (Sandbox Code Playgroud)

Jor*_*ies 3

您的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!";
}
Run Code Online (Sandbox Code Playgroud)