Reputation: 309
I'm trying to work with the Dog API, trying to get a random breed image and display it in a ListTile
Model class
class DogData {
DogData ({this.message, this.status});
String message;
String status;
factory DogData.fromJson(Map<String, dynamic> json) => DogData (
message: json["message"],
status: json["status"],
);
Map<String, dynamic> toJson() => {
"message": message,
"status": status,
};
}
There is an error inside the ListTile, undefined name "index". Where did I go wrong and how can I fix it?
import 'package:flutter/material.dart';
import 'package:practice_5/model/breedModel.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async';
import 'package:flutter/foundation.dart';
class BreedListTile extends StatelessWidget {
Future<List<DogData>> fetchDogs(http.Client client) async {
final response = await client.get('https://dog.ceo/api/breeds/image/random');
return compute(parseDog, response.body);
}
List<DogData> parseDog(responseBody) {
final parsed = jsonDecode(responseBody) as List;
return parsed.map<DogData>((json) => DogData.fromJson(json)).toList();
}
BreedListTile({Key key, List<DogData> dogList})
: _dogList = dogList,
super(key: key);
final List<DogData> _dogList;
@override
Widget build(BuildContext context) {
return Card(
child: ListTile(
title: Text('Test title'),
subtitle: Text('Test subtitle'),
leading: Container(
child: Image.asset(_dogList[index].message),
),
onTap: () {},
),
);
}
}
Upvotes: 0
Views: 327
Reputation: 7650
You need to use your ListTile
's under a ListView
widget. Try something like this:
ListView.builder
(
itemCount: _dogList.length,
itemBuilder: (BuildContext ctxt, int index) {
return Card(
child: ListTile(
title: Text('Test title'),
subtitle: Text('Test subtitle'),
leading: Container(
child: Image.network(_dogList[index].message),
),
onTap: () {},
),
)
Edit:
By the way, you are trying to get an image from a URL. So, you need to use Image.network('url')
. Read more.
Upvotes: 1