在显示图片之前,我想从NetworkImage
或Image.network
中获取属性值,例如宽度和高度。
我找到了以下好的帖子,但它们不起作用。 它得到了大小值,但图像没有在FutureBuilder
中加载。
我的代码如下:
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;
}
}
结果是; - 屏幕只显示 "正在加载...",图片没有被加载。 -
print
输出如下。这应该意味着,在加载图像之前 FutureBuilder
被调用了两次,我们可以得到宽度,但在那之后 FutureBuilder
没有被调用。false
false
112
环境:
- Flutter 1.13.0 • dev 频道 (因为需要支持 Flutter web)
- Chrome 版本 79.0.3945.79
Image.memory
显示它。 - Abion47