Last active
June 16, 2019 08:55
-
-
Save szotp/f136b2f096555ca13bcddbeae2bd48ca to your computer and use it in GitHub Desktop.
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 'dart:async'; | |
import 'dart:ui'; | |
import 'package:flutter/widgets.dart'; | |
// Usage: | |
Future<void> main() async { | |
await precacheImageCustom(SplashPage.image); | |
await precacheImageCustom(LoginPage.backgroundImage); | |
runApp(App()); | |
} | |
Future<void> precacheImageCustom( | |
ImageProvider provider, { | |
Size size, | |
ImageErrorListener onError, | |
}) { | |
WidgetsFlutterBinding.ensureInitialized(); | |
final ImageConfiguration config = ImageConfiguration( | |
devicePixelRatio: MediaQueryData.fromWindow(window).devicePixelRatio, | |
); | |
final Completer<void> completer = Completer<void>(); | |
final ImageStream stream = provider.resolve(config); | |
void listener(ImageInfo image, bool sync) { | |
completer.complete(); | |
stream.removeListener(listener); | |
} | |
void errorListener(dynamic exception, StackTrace stackTrace) { | |
completer.complete(); | |
stream.removeListener(listener); | |
if (onError != null) { | |
onError(exception, stackTrace); | |
} else { | |
FlutterError.reportError(FlutterErrorDetails( | |
context: 'image failed to precache', | |
library: 'image resource service', | |
exception: exception, | |
stack: stackTrace, | |
silent: true, | |
)); | |
} | |
} | |
stream.addListener(listener, onError: errorListener); | |
return completer.future; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment