我只是在尝试LayoutBuilder
和FutureBuilder
时遇到了一种情况。如果我将FutureBuilder
放在除LayoutBuilder
之外的其他小部件中,那么一切都很好,将来只能解决一次。但是,当我将FutureBuilder
放入LayoutBuilder
中时, future 会无限解决,并且永远不会绘制最终的小部件。
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Photo View example',
theme: theme,
home: new Scaffold(
body: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return ImagePainter();
}
),
),
);
}
}
class ImagePainter extends StatelessWidget{
Future<ui.Image> loadImage() async {
ByteData data = await rootBundle.load("graphics/test.jpg");
if (data == null) {
print("data is null");
} else {
var codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
var frame = await codec.getNextFrame();
return frame.image;
}
}
@override
Widget build(BuildContext context) {
return Container(
child: FutureBuilder(
future: loadImage(),
builder: (BuildContext context, AsyncSnapshot<ui.Image> snapshot) {
switch(snapshot.connectionState) {
case ConnectionState.waiting :
return Center(child: Text("loading..."),);
default:
if (snapshot.hasError) {
return Center(child: Text("error: ${snapshot.error}"),);
} else {
print("data: ${snapshot.data}");
return Placeholder(); //just for testing
}
}
},
),
);
}
}
可以解释吗?,或者我做错了什么。
最佳答案
class ImagePainter extends StatelessWidget{
Future<ui.Image> loadImage() async {
ByteData data = await rootBundle.load("graphics/test.jpg");
if (data == null) {
print("data is null");
} else {
var codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
var frame = await codec.getNextFrame();
return frame.image;
}
}
@override
Widget build(BuildContext context) {
return Container(
child: FutureBuilder(
future: loadImage(),
builder: (BuildContext context, AsyncSnapshot<ui.Image> snapshot) {
switch(snapshot.connectionState) {
case ConnectionState.waiting :
print("data: ${snapshot.data}");
//return Center(child: Text("loading..."),);
default:
if (snapshot.hasError) {
return Center(child: Text("error: ${snapshot.error}"),);
} /*else {
print("data: ${snapshot.data}");
return Placeholder(); //just for testing
}*/
}
},
),
);
}
}