Skip to content

Instantly share code, notes, and snippets.

@cdmunoz
Last active May 11, 2023 14:51
Show Gist options
  • Save cdmunoz/79418ee203f9c902a90dc9ad9ff0e0a4 to your computer and use it in GitHub Desktop.
Save cdmunoz/79418ee203f9c902a90dc9ad9ff0e0a4 to your computer and use it in GitHub Desktop.
/// this is part of a stateful widget, that uses Isolates.compute to do a heavy task, in this case download and
/// display an image from internet in parallel.
/// this will help to improve performance for our scenario when a chat messages screen should display all messages
class _MessagesImageState extends State<MessagesImage> {
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () {
// onTap logic
},
child: FutureBuilder<Widget>(
future: _buildIsolatedWidget(widget.url),
builder: (BuildContext context, AsyncSnapshot<Widget> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
return const Center(child: Icon(Icons.error));
} else {
return snapshot.requireData;
}
} else {
return _buildPlaceHolder();
}
},
),
);
}
// this is the function that creates a Compute Isolate that calls the
// CachedNetworkImage widget
Future<Widget> _buildIsolatedWidget(String url) async {
return compute(_buildNetworkImage, url);
}
static Widget _buildNetworkImage(String imageUrl) {
return AspectRatio(
aspectRatio: 4 / 3,
child: Hero(
tag: imageUrl,
child: CachedNetworkImage(
imageUrl: imageUrl,
placeholder: (context, url) {
return const Center(child: CircularProgressIndicator());
},
errorWidget: (context, url, error) {
return const Center(child: Icon(Icons.error));
},
),
),
);
}
Widget _buildPlaceHolder() {
return const Center(child: CircularProgressIndicator());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment