When displaying images using the default Image
widget, you might notice theysimply pop onto the screen as they’re loaded. This might feel visually jarringto your users.
Instead, wouldn’t it be nice if you could display a placeholder at first,and images would fade in as they’re loaded? You can use theFadeInImage
Widget packaged with Flutter for exactly this purpose.
FadeInImage
works with images of any type: in-memory, local assets, or imagesfrom the internet.
In-Memory
In this example, you’ll use thetransparent_imagepackage for a simple transparent placeholder.
FadeInImage.memoryNetwork(
placeholder: kTransparentImage,
image: 'https://picsum.photos/250?image=9',
);
Complete example
import 'package:flutter/material.dart';
import 'package:transparent_image/transparent_image.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final title = 'Fade in images';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Stack(
children: <Widget>[
Center(child: CircularProgressIndicator()),
Center(
child: FadeInImage.memoryNetwork(
placeholder: kTransparentImage,
image: 'https://picsum.photos/250?image=9',
),
),
],
),
),
);
}
}
From asset bundle
You can also consider using local assets for placeholders. First, add the assetto the project’s pubspec.yaml
file (for more details seeAssets and images):
flutter:
assets:
+ - assets/loading.gif
Then, use theFadeInImage.assetNetwork()constructor:
FadeInImage.assetNetwork(
placeholder: 'assets/loading.gif',
image: 'https://picsum.photos/250?image=9',
);
Complete example
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final title = 'Fade in images';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: FadeInImage.assetNetwork(
placeholder: 'assets/loading.gif',
image: 'https://picsum.photos/250?image=9',
),
),
),
);
}
}