I have a function which returns images directory path, it performs some additional check like if directory exists or not, then it behaves accordingly.
Here is my code:
Future<String> getImagesPath() async {
final Directory appDir = await getApplicationDocumentsDirectory();
final String appDirPath = appDir.path;
final String imgPath = appDirPath + '/data/images';
final imgDir = new Directory(imgPath);
bool dirExists = await imgDir.exists();
if (!dirExists) {
await new Directory(imgPath).create(recursive: true);
}
return imgPath;
}
This piece of code works as expected, but I'm having issue in getting value from Future
.
Case Scenario:
I have data stored in local database and trying to display it, inside listview. I'm using FutureBuilder
, as explained in this answer. Each data row has an image connected with it (connected means, the image name is stored in db).
Inside Widget build
method, I have this code:
@override
Widget build(BuildContext context) {
getImagesPath().then((path){
imagesPath = path;
print(imagesPath); //prints correct path
});
print(imagesPath); //prints null
return Scaffold(
//removed
body: FutureBuilder<List>(
future: databaseHelper.getList(),
initialData: List(),
builder: (context, snapshot) {
return snapshot.hasData
? ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (_, int position) {
final item = snapshot.data[position];
final image = "$imagesPath/${item.row[0]}.jpg";
return Card(
child: ListTile(
leading: Image.asset(image),
title: Text(item.row[1]),
subtitle: Text(item.row[2]),
trailing: Icon(Icons.launch),
));
})
: Center(
child: CircularProgressIndicator(),
);
}));
}
Shifting return Scaffold(.....)
inside .then
doesn't work. Because widget build returns nothing.
The other option I found is async/await
but at the end, same problem, code available below:
_getImagesPath() async {
return await imgPath();
}
Calling _getImagesPath()
returns Future
, instead of actual data.
I beleive there is very small logical mistake, but unable to find it myself.
FutureBuilder
in your code... so are you using it orStatefulWidget
for exmple? – AntitypeStatefulWidget
and I've shared complete code, please lemme know if you need more info. – RespondentFutureBuilder
, so my question: is it a right code? or maybe you are usingStatefulWidget
? – AntitypeFutureBuilder
in the code, and you also know to make_getImagesPath
an async function. Is there any errors when you combine these two? – NeoplastyStatefulWidget
. TheWidget build
method is insideStatefulWidget
class. – RespondentimagesPath
isnull
at run time. – Respondent