【问题标题】:'String' not subtype of 'int' flutter“字符串”不是“int”颤动的子类型
【发布时间】:2019-06-08 07:24:19
【问题描述】:

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

我用这个code 写了我的一些更改.. 在链接中他有我的results 数组我没有所以我离开了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();
  }
}

【问题讨论】:

  • 哪一行导致这个错误?

标签: dart flutter


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    忘记在请求标头中添加接受类型时出现此错误

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-30
      • 1970-01-01
      • 2021-08-22
      • 2021-08-09
      • 1970-01-01
      • 2021-08-12
      • 2020-09-29
      • 2021-08-02
      相关资源
      最近更新 更多