Flutter-LayoutBuilder内的FutureBuilder调用未来很多次

时间:2018-07-17 13:14:30

标签: android layout dart flutter

在尝试LayoutBuilderFutureBuilder时遇到了一个问题。如果我将FutureBuilder放在LayoutBuilder以外的小部件中,那么一切都很好,而未来只能解决一次。但是,当我将FutureBuilder放在LayoutBuilder内时,未来将无限解决,并且永远不会绘制最终的小部件。

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
              }
            }
          },
        ),
    );
  }
}

所以可以解释吗?,或者我做错了什么事。

1 个答案:

答案 0 :(得分:-1)

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
           }*/
         }
        },
      ),
   );
 }
}