skip to Main Content

my app got error "Type ‘String’ is not a subtype of type ‘int’ of ‘index’. This is because i want to get data with a string id. But i use listview.builder and it can’t accept a string data
this is my code

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  late Future<List<Agent>> agents;

  @override
  void initState() {
    super.initState();
    agents = fetchAgents();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('My Anime List'),
        ),
      body: Column(
          children: [
              FutureBuilder(
                builder: (context, AsyncSnapshot<List<Agent>> snapshot) {
                  if (snapshot.hasData) {
                    return Expanded(
                      child: ListView.builder(
                        itemCount: snapshot.data?.length,
                        itemBuilder: (BuildContext context,  index) {
                          return Card(
                            child: ListTile(
                              contentPadding: const EdgeInsets.symmetric(
                                  horizontal: 20.0, vertical: 10.0),
                              leading: CircleAvatar(
                                radius: 30,
                                backgroundImage: NetworkImage(
                                    snapshot.data![index].displayIconSmall),
                              ),
                              title: Text(snapshot.data![index].displayName),
                              subtitle: Text('Role: ${snapshot.data![index].role.displayName}'),
                              onTap: () {
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (context) => DetailPage(
                                        item: snapshot.data![index].uuid,
                                        title: snapshot.data![index].displayName,
                                        role: snapshot.data![index].role.displayName,
                                        image: snapshot.data![index].displayIconSmall,
                                        description: snapshot.data![index].description,),
                                  ),
                                );
                              },
                            ),
                          );
                        },
                      ),
                    );
                  } else if (snapshot.hasError) {
                    return Center(child: Text('${snapshot.error}'));
                  }
                  return const CircularProgressIndicator();
                },
                future: agents,
              ),
          ],
        ),
    );
  }
}
class Agent {
  final String uuid;
  final String displayName;
  final String description;
  final String displayIcon;
  final String displayIconSmall;
  final bool isPlayableCharacter;
  Role role;

  Agent({
    required this.uuid,
    required this.displayName,
    required this.description,
    required this.displayIcon,
    required this.displayIconSmall,
    required this.isPlayableCharacter,
    required this.role
  });

  factory Agent.fromJson(Map<String, dynamic> json) {
    return Agent(
      uuid: json['uuid'],
      displayName : json['displayName'],
      description : json['description'],
      displayIcon : json['displayIcon'],
      displayIconSmall : json['displayIconSmall'],
      isPlayableCharacter : json['isPlayableCharacter'],
      role : json['role'],
      );
  }
  Map<String, dynamic> toJson() => {
        'uuid': uuid,
        'displayName': displayName,
        'description': description,
        'displayIcon': displayIcon,
        'displayIconSmall': displayIconSmall,
        'isPlayableCharacter': isPlayableCharacter,
        'role': role
      };
}

class Role{
  final String uuid;
  final String displayName;
  final String description;

   Role({
    required this.uuid,
    required this.displayName,
    required this.description,
  });

  factory Role.fromJson(Map<String, dynamic> json) {
    return Role(
      uuid: json['uuid'],
      displayName : json['displayName'],
      description : json['description'],
      );
  }

  Map<String, dynamic> toJson() => {
        'uuid': uuid,
        'displayName': displayName,
        'description': description,
      };
}
Future<List<Agent>> fetchAgents() async {
  final response =
      await http.get(Uri.parse('https://valorant-api.com/v1/agents'));

  if (response.statusCode == 200) {
    var jsonResponse = json.decode(response.body)['data'];
    var data = jsonResponse["data"];
    if(data is Map) {
        Role user = Role(
          uuid:["uuid"].toString(),
          displayName:["displayName"].toString(),
          description:["description"].toString(),
        );
        return jsonResponse.map((role) => Agent.fromJson(role)).toList();
      };
    return jsonResponse.map((agent) => Agent.fromJson(agent)).toList();
  } else {
    throw Exception('Failed to load data');
  }
}

i already try to change it to integer but it can’t since listview.build must have index and index must be integer. I expecting the data can be pass because the uid for the api data is string type

3

Answers


  1. you can turn a String id like "818" to an int with the following:

    String uuid = "818";
    int.parse(uuid) //  818
    
    Login or Signup to reply.
  2.  uuid: int.parse(json['uuid'].toString()),
          displayName : json['displayName'].toString(),
          description : json['description'].toString(),
          displayIcon : json['displayIcon'].toString(),
          displayIconSmall : json['displayIconSmall'].toString(),
          isPlayableCharacter : json['isPlayableCharacter'].toString(),
          role : json['role'].toString(),
    
    Login or Signup to reply.
  3. If you’re expecting the response from https://valorant-api.com/v1/agents to look like this

    {
      "status":200,
      "data":[
        {
          "uuid":"dade69b4-4f5a-8528-247b-219e5a1facd6",
          "displayName":"Fade",
          ...
        },
        ...
      ]
    }
    

    then I believe the problem is in your fetchAgents() function — specifically in these lines:

    var jsonResponse = json.decode(response.body)['data'];
    var data = jsonResponse["data"];
    

    If you use strong typing for the variables and break down the steps, you’ll see:

    List<dynamic> jsonResponse = json.decode(response.body)['data'];
    dynamic data = jsonResponse["data"];  // Error here; expects int
    

    Solution:

    Map<String, dynamic> jsonResponse = json.decode(response.body);
    dynamic? data = jsonResponse['data'];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search