【问题标题】:Flutter : I'm trying to fetch api data into listview , got that error " type 'String' is not a subtype of type 'int' of 'index' "Flutter:我正在尝试将 api 数据提取到 listview 中,出现错误“类型'String'不是'index'类型'int'的子类型”
【发布时间】:2020-11-13 20:07:20
【问题描述】:

大家好,我是 Flutter 的新手,我正在尝试将 api 数据提取到 listview 中,出现以下错误
'String' 类型不是 'index' 的 'int' 类型的子类型, “String”类型不是“index”的“int”类型的子类型 “String”类型不是“index”的“int”类型的子类型 不知道该怎么办。 在此先感谢。

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'dart:convert';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  Future<List<User>> getData() async {
    var data = await http.get("https://jsonplaceholder.typicode.com/todos");
    var jsonData = json.decode(data.body);

    List<User> users = [];
    for (var u in jsonData.) {
      User user = new User(u["title"], u["userId"], u["completed"], u["id"]);
      users.add(user);
    }
    print(users.length);
    return users;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Api Calling'),
      ),
      body: Container(
        child: FutureBuilder(
          future: getData(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            if (snapshot.data == null) {
              return Container(
                child: Text("data loading"),
              );
            } else {
              return ListView.builder(
                itemCount: snapshot.data.length,
                itemBuilder: (BuildContext context, int index) {
                  return ListTile(
                    title: Text("${snapshot.data["index"].id}"),
                  );
                },
              );
            }
          },
        ),
      ),
    );
  }
}

class User {
  final int userId;
  final int id;
  final String title;
  final bool completed;
  User(this.title, this.userId, this.completed, this.id);
}

【问题讨论】:

    标签: flutter


    【解决方案1】:

    这应该是这样的:“索引”(字符串类型)->索引(整数类型)

    title: Text("${snapshot.data[index].id}"),
    

    【讨论】:

      【解决方案2】:

      ListView.builder

      尝试将"index" 更改为index..

      这里..

      title: Text("${snapshot.data["index"].id}"),
      

      改成..

      title: Text("${snapshot.data[index].id}"),
      

      原因: 数组(列表)的索引应该是int..但是,当你把它放在引号(“”)中时,它将被视为string,这就是导致你的错误的原因..

      希望它应该有效,您的问题将得到解决..随时要求澄清:)

      【讨论】:

      • 非常感谢您的解决方案和澄清
      猜你喜欢
      • 2021-05-10
      • 2020-04-22
      • 2022-09-27
      • 2020-10-02
      • 2021-12-15
      • 1970-01-01
      • 2019-04-24
      • 2022-11-25
      • 2021-03-29
      相关资源
      最近更新 更多