I want to get attribute values, such as width and height, from NetworkImage
or Image.network
before displaying the image.
I found the following good posts, but it doesn't work. It got the size values, but the image is not loaded in FutureBuilder
.
- How do I determine the width and height of an image in Flutter?
- How do I tell when a NetworkImage has finished loading?
My code is as below;
import 'dart:async';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: FutureBuilder(
future: _getImage(),
builder: (BuildContext context, AsyncSnapshot<Image> snapshot) {
print(snapshot.hasData);
if (snapshot.hasData) {
return snapshot.data;
} else {
return Text('Loading...');
}
},
),
),
);
}
Future<Image> _getImage() async {
final Completer completer = Completer();
final String url = 'http://images-jp.amazon.com/images/P/4101098018.09.MZZZZZZZ';
final image = NetworkImage(url);
image.resolve(ImageConfiguration())
.addListener(ImageStreamListener((ImageInfo info, bool isSync) {
print(info.image.width);
completer.complete(info.image);
}));
return completer.future;
}
}
The result is;
- The screen only shows "Loading..." and the image is not loaded.
- print
output is as below. This should means, FutureBuilder
is called twice before loading the image, and we can get the width but FutureBuilder
is not called after that.
false
false
112
Environment:
- Flutter 1.13.0 • channel dev (due to flutter web)
- Chrome Version 79.0.3945.79