In this Flutter app, I want to build a list of items with thumbnails that are stored as file names in the database. The files are stored inside the application’s directory and only the name is saved in the database.
When I build the list, I want to get the application’s directory then join it with the file name. But I don’t know how to do it because getApplicationDocumentsDirectory()
is asynchronous and it doesn’t return the value when I need it (before using ListView.builder
)
My code, to make it clearer
class _ItemsWidgetState extends State<ItemsWidget> {
String? appDir;
@override
void initState() {
// this seems like the only place where I can get it
getApplicationDocumentsDirectory().then((value) => appDir = value.path);
super.initState();
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: widget.items,
initialData: const [],
builder: (context, snapshot) {
return snapshot.hasData && snapshot.data!.isNotEmpty
? ListView.builder(
itemCount: snapshot.data?.length,
itemBuilder: (_, int index) {
final Item item = snapshot.data![index];
// $aappDir is NULL here
return ListTile(
leading: Image.file(File('$appDir/${item.thumbnailName}')),
title: Text(item.name,),
);
})
: Center(child: Text('No items added'),),
);
});
}
}
As you can see, appDir
is null and initState()
does not change that, even though it does get the directory. I need to understand better how this works and how can I make this work
2
Answers
Try as follows:
getApplicationDocumentsDirectory().then((value) => setState(() => appDir = value.path));