Skip to content

Instantly share code, notes, and snippets.

@riscait
Created May 25, 2022 20:17
Show Gist options
  • Save riscait/c26d7395c1fb3e76a61a6893c50ea1a9 to your computer and use it in GitHub Desktop.
Save riscait/c26d7395c1fb3e76a61a6893c50ea1a9 to your computer and use it in GitHub Desktop.
Flutter precacheImage example
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({
super.key,
required this.title,
});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late NetworkImage _networkImage;
@override
void initState() {
super.initState();
_networkImage = const NetworkImage(
'https://images.unsplash.com/photo-1653184849936-f64ad1081f96',
);
}
@override
void didChangeDependencies() {
precacheImage(_networkImage, context);
super.didChangeDependencies();
}
void _showImageDialog() {
showDialog<void>(
context: context,
builder: (context) {
return SimpleDialog(
children: [
Image(image: _networkImage),
],
);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(_networkImage.url),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _showImageDialog,
child: const Icon(Icons.add),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment