How to Show an Local image till the NetworkImage() Loads Up in flutter?
You may want to try a FadeInImage
wrapped in a ClipOval
. FadeInImage
provides a placeholder
property you can use while the network image is loading.
Note: ClipOval
can be expensive if you do it a lot, so use it sparingly.
Use a StateflWidget
and you can add a listener
to the ImageStream
and override the initState
to trigger a replacement between the local image and the one obtained from the internet when it is fully loaded.
I have used a high resolution image to show the loading time:
var _loadImage = new AssetImage(
'assets/img/basic2-090_loader_loading-512.png');
var _myEarth = new NetworkImage(
"http://qige87.com/data/out/73/wp-image-144183272.png");
bool _checkLoaded = true;
@override
void initState() {
_myEarth.resolve(new ImageConfiguration()).addListener((_, __) {
if (mounted) {
setState(() {
_checkLoaded = false;
});
}
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
body: new Center(child: new Container(
decoration: new BoxDecoration(shape: BoxShape.circle,),
height: 80.0,
width: 80.0,
child: new CircleAvatar(
backgroundColor: Theme
.of(context)
.scaffoldBackgroundColor,
backgroundImage: _checkLoaded ? _loadImage : _myEarth,
),)
)
);
}
}
There is a new official widget for this now!
First, create a folder called assets
in the project root directory.
Then, mention the folder in pubspec.yaml
file (also found in the project root directory):
flutter:
uses-material-design: true
assets:
- assets/
You can put a picture there, for example, put this as ./assets/loading.gif
.
(If you changed files in assets folder, hot reload won't work. Make sure you restart the app entirely.)
Now you can refer to the loading file in the code:
FadeInImage.assetNetwork(
placeholder: 'assets/loading.gif',
image: 'https://github.com/flutter/website/blob/master/src/_includes/code/layout/lakes/images/lake.jpg?raw=true',
);
For more details: https://flutter.io/docs/cookbook/images/fading-in-images#from-asset-bundle