I wanted to display images from Unsplash API in my flutter application. I followed steps from a youtube tutorial, the code ran without any errors but the images are not getting displayed in the application.
I have attached the code below (<api_access_key> contained the access key for the unsplash API.)
I expect the output to be a list of images from the Unsplash API. The code is done in Android Studio.
I'm new to APIs and would appreciate any help.
Thanks in advance. `
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class wpList extends StatefulWidget {
@override
_wpListState createState() => _wpListState();
}
class _wpListState extends State<wpList> {
List data = [];
List<String> wpUrl=[];
bool showing = false;
getData() async{
http.Response response= await http.get(Uri.parse('https://api.unsplash.com/photos/?client_id=<api_access_key>'));
data = json.decode(response.body);
_assign();
setState(() {
showing = true;
});
}
_assign(){
for(var i=0; i<data.length; i ){
wpUrl.add(data.elementAt(1)["urls"]["regular"]);
print(wpUrl);
}
}
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: data.length,
itemBuilder: (context, index){
return Column(
children: [
SizedBox(
height: 10,
),
Expanded(
flex: 6,
//height: 50,
//color: Colors.amber,
child: Container(
child: !showing? CircularProgressIndicator():Image(image: NetworkImage(wpUrl.elementAt(index))),
)
)
],
);
});
}
}
`
CodePudding user response:
you have written code well to show the data assuming that you already have initial data. But you don't have any initial data. When the code runs, data = []
is an empty list, and data.length
in the ListView builder does not show any data.
We should call getData()
before rendering the ui(we should populate data array before rendering the ui). We can do this by calling getData()
from init function as below.
@override
initState() {
super.initState();
getData();
}
But there is a small chance that images do get displayed in this case also.
Reason:
your getData() method runs in an asynchronous thread as it is an async function. So, getData()
code gets into the asynchronous thread for execution. But the control doesn't wait for the completion of getData()
and skips to the next line (in this case build method).
So your images get displayed only if the network request in the getData()
method does not take too much time so that data gets initialized before the control reaches the build method.
Fix
You can initialize data inside setState(){} so that rendering takes place once again when data is initialized
you can call await method inside initState() so that control waits until the complete execution of getData() function. But you get error in this case that we can not add async modifier to init function which can be solved using below reference. https://www.fluttercampus.com/guide/63/how-to-run-async-await-code-in-initstate-flutter-app/
Please upvote and accept the answer if useful
CodePudding user response:
You never called the function to get the data
API calls usually are done from initState
(more about initState)
Try adding this above your build
method
@override
initState() {
super.initState();
getData();
}