I am creating a file manager in flutter for learning purpose. I have just started learning flutter so i don't have much knowledge about it.
My issue is that I want to display thumbnails for images in a folder, for that i am calling a function written in android native code using a FutureBuilder in ListView. It is working fine but whenever I open a directory with lots of images, it freezes the UI for some time & I am unable to scroll it for that time even though thumbnails are called asynchronously.
Me code of Listview:-
@override
Widget build(BuildContext context) {
return new ListView.builder(
itemBuilder: (itemContext, i) {
if (_filesList != null && i < _filesList.length) {
String currDir = _filesList[i]['path'];
return new ListTile(
title: new Text(_filesList[i]['name']),
leading: (_filesList[i]['isDir'] == "false")
? new FutureBuilder<Uint8List>(
future: _getThumbnail(currDir),
builder: (BuildContext context,
AsyncSnapshot<Uint8List> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return new Container(
decoration: new BoxDecoration(
color: Colors.brown,
borderRadius: new BorderRadius.circular(20.0),
),
width: 30.0,
height: 30.0,
);
default:
if (snapshot.hasError)
return new Container(
decoration: new BoxDecoration(
color: Colors.brown,
borderRadius: new BorderRadius.circular(20.0),
),
width: 30.0,
height: 30.0,
);
else {
return new Image.memory(snapshot.data);
}
}
},
)
: new Container(
decoration: new BoxDecoration(
color: (_filesList[i]['isDir'] == "true")
? Colors.yellow
: Colors.brown,
borderRadius: new BorderRadius.circular(20.0),
),
width: 30.0,
height: 30.0),
onTap: () {
setState(() {
_currentDir = currDir;
});
_getFilesList(currDir);
},
);
} else {
return null;
}
},
);
}
Code for _getThumbnail():-
Future <Uint8List> _getThumbnail(path) async {
try {
String thumbnailString =
await channel.invokeMethod("getThumbnail", {"path": path});
thumbnailString = thumbnailString.replaceAll('\n', '');
Uint8List bytes = BASE64.decode(thumbnailString);
return bytes;
} on PlatformException catch (e) {
print("Files Not Found $e{e.message}");
return null;
}
}
Even though calls are asynchronous in Flutter, the code on Android that handles getThumbnail
can block the UI thread, leading to frozen loading or choppy scrolling. A solution is to use AsyncTask to build/fetch the thumbnails in doInBackground
and return the result in onPostExecute
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.