Last active
May 26, 2022 01:02
-
-
Save riscait/ad14d0b0367dfee7a452cf4a1fbe43f4 to your computer and use it in GitHub Desktop.
Flutter precacheImage example with Flutter Hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'package:flutter_hooks/flutter_hooks.dart'; | |
void main() => runApp(const MyApp()); | |
class MyApp extends StatelessWidget { | |
const MyApp({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
theme: ThemeData( | |
useMaterial3: true, | |
), | |
home: MyHomePage(), | |
); | |
} | |
} | |
class MyHomePage extends HookWidget { | |
MyHomePage({ | |
super.key, | |
String url = 'https://images.unsplash.com/photo-1653184849936-f64ad1081f96', | |
}) : networkImage = NetworkImage(url); | |
final NetworkImage networkImage; | |
@override | |
Widget build(BuildContext context) { | |
useEffect( | |
() { | |
WidgetsBinding.instance.addPostFrameCallback((_) async { | |
precacheImage(networkImage, context); | |
}); | |
return null; | |
}, | |
const [], | |
); | |
void _showImageDialog() { | |
showDialog<void>( | |
context: context, | |
builder: (context) { | |
return SimpleDialog( | |
children: [ | |
Image(image: networkImage), | |
], | |
); | |
}, | |
); | |
} | |
return Scaffold( | |
appBar: AppBar( | |
title: const Text('Demo'), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: const [ | |
Text('Sample'), | |
], | |
), | |
), | |
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