Reputation: 3008
I am trying to parse and render remote API's result. Here is my API looks like:
{
"count": 2,
"next": null,
"previous": null,
"results": [
{
"image": "https://example.com/asas"
},
{
"image": "https://example.com/as"
}
]
}
model for parsing json:
class SliderModel {
final String count;
final List<Result> results;
SliderModel({this.count, this.results});
factory SliderModel.fromJson(Map<String, dynamic> parsedJson) {
var list = parsedJson['results'] as List;
List<Result> imagesList = list.map((i) => Result.fromJson(i)).toList();
return SliderModel(
count: parsedJson['count'],
results: imagesList
);
}
}
class Result {
final String image;
Result({this.image});
factory Result.fromJson(Map<String, dynamic> parsedJson) {
return Result(
image: parsedJson['image']
);
}
}
and then the API calling and render method:
class _HomeState extends State<Home> {
SliderModel slider = SliderModel();
@override
Widget build(BuildContext context) {
return
// some codes
body: FutureBuilder(
future: this._loadSlider(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
case ConnectionState.active: {
return Center(
child: CircularProgressIndicator(),
);
}
case ConnectionState.done: {
if (snapshot.hasError) {
DioError error = snapshot.error;
String message = error.message;
if (error.type == DioErrorType.CONNECT_TIMEOUT)
message = 'Connection Timeout';
else if (error.type == DioErrorType.RECEIVE_TIMEOUT)
message = 'Receive Timeout';
else if (error.type == DioErrorType.RESPONSE)
message =
'404 server not found ${error.response.statusCode}';
return Text('Error: ${message}');
}
}
}
return CarouselSlider(
height: 200.0,
items: slider.results.map((i) {
return Builder(
builder: (BuildContext context) {
return Container(
width: MediaQuery.of(context).size.width,
margin: EdgeInsets.symmetric(horizontal: 1.0),
decoration: BoxDecoration(
color: Colors.amber
),
child: Text('text $i', style: TextStyle(fontSize: 16.0),)
//child: Image.network(i, fit: BoxFit.fill),
);
},
);
}).toList(),
);
},),
}
Future<dynamic> _loadSlider() async{
try {
Response response = await Dio().get("https://example.com/api/slider/");
//print(response.data['results'][0]['image']);
Map<String, dynamic> data = json.decode(response.data);
slider = SliderModel.fromJson(data);
return slider;
} catch (e) {
print(e);
}
}
}
When I tried to run the app it throws this message :
NoSuchMethodError: The method 'map' was called on null.
Receiver: null
Tried calling:
map<Builder>(Closure: (Result) => builder)
Upvotes: 1
Views: 396
Reputation: 3003
@pyprism, not sure why you're calling slider.results
. I think it should be snapshot.data.results
instead. Your loaded SliderModel
instance will be in snapshot.data
. You might also wanna make sure snapshot has data with if (snapshot.hasData) {
.
Upvotes: 1