0

I am trying to set expanded height according to image from URL.

I implemented a Future function.

Future<double> _calculateImageRatio(String url) async {
 
  double ratioX = 0.0;
  Completer<Size> completer = Completer();
  Image image = Image.network(url);
  image.image.resolve(ImageConfiguration()).addListener(
    ImageStreamListener(
      (ImageInfo image, bool synchronousCall) {
        var myImage = image.image;
        Size size = Size(myImage.width.toDouble(), myImage.height.toDouble());
        completer.complete(size);
        ratioX = size.height / size.width;
      },
    ),
  );
  return ratioX;
}

Although this function returns double value, I can not run the code as it gives

The argument type 'num' can't be assigned to the parameter type 'double?'.

error.

in SliverAppBar.

     SliverAppBar _customAppBar(BuildContext context) {
         return SliverAppBar(
          
          expandedHeight: 150 * _calculateImageRatio("url-of-image"),//This line is problematic, the error occurs in this line.
      
       ...
       ...
       ...

        );
      }

How can I solve my problem? I looked FutureBuilder but I can not solved my problem, I could not understand how can I implement FutureBuilder here, or any other solution?

gurkan stack
  • 413
  • 1
  • 15
  • 43

1 Answers1

0

I think you need to modify your function

Future<double> _calculateImageRatio(String url) {
    Image image = Image.network(url);
    Completer<double> completer = Completer();
    image.image.resolve(ImageConfiguration()).addListener(
      ImageStreamListener(
        (ImageInfo image, bool synchronousCall) {
          var myImage = image.image;
          completer.complete(myImage.width.toDouble() / myImage.height.toDouble());
        },
      ),
    );
    return completer.future;
  }

then wrap your SliverAppBar with a FutureBuilder

return FutureBuilder<double>(
      future: _calculateImageRatio("url-of-image"),
      builder: (BuildContext context, AsyncSnapshot<double> snapshot) {
        if (snapshot.hasData) {
          return SliverAppBar(
            expandedHeight: 150.00 * snapshot.data!,
...
...
          );
        } else {
          return SizedBox(
            child: CircularProgressIndicator(),
            width: 60,
            height: 60,
          );
        }
      },
    );
rosh-dev851
  • 534
  • 4
  • 8