Home > Software engineering >  How to format image string from a method in flutter
How to format image string from a method in flutter

Time:03-06

I am having a class NetworkHandler.dart with a method getImage

This is the class

class NetworkHandler{
 String imgUrl = "http://10.0.2.2:5000";
 NetworkImage getImage(String imageName) {
    String url = imgUrl   imageName;
    return NetworkImage(url);
  }
}

So when trying to use the getImage method in one of my widgets like this

  Widget _buildBottomInfo(BuildContext context,
      {required String ImgUrl}) {
    return SliverToBoxAdapter(
      child: Column(
                  children: <Widget>[
                    Container(
                      padding: EdgeInsets.only(top: 20),
                      height: 145,
                      width: MediaQuery.of(context).size.width - 60,
                      child: CachedNetworkImage(
                        imageUrl: ImgUrl, //
                        fit: BoxFit.fitWidth,
                      ),
                    ),
                  ],
                ),
    );
  }


  _buildBottomInfo(
                  context,
     ImgUrl: NetworkHandler().getImage(vendorController.vendor.value.v_banner.toString())
     .toString(),
  ),

I got an error showing

'Illegal scheme character (at character 13)
NetworkImage("http://10.0.2.2:5000/public/W52xyq4Hkd-refil-store1.jpeg", sc...'

but when I use it directly without the getImage method like this

'${NetworkHandler().imgUrl   vendorController.vendor.value.v_banner!}',

It works fine, and the image is displayed

So how can I use it with the getImage method in my widget?

CodePudding user response:

You're passing URL that is string on _buildBottomInfo and it will be used on CachedNetworkImage, everything is fine until now but while doing

NetworkHandler().getImage(vendorController.vendor.value.v_banner.toString())
     .toString()

You are forcing NetworkHandler to be a string. While it is not a string, it produces the error.

You can get URL by from NetworkImage

NetworkHandler().getImage(...).url

You also make this simpler by making static method,

class NetworkHandler {
  static const _imgUrl = "http://10.0.2.2:5000";
  static String getImageUrlString(String imageName) {
    String url = _imgUrl   imageName;
    return url;
  }
}

Now to use this

 NetworkHandler.getImageUrlString("rest_imageName"),

in your case, rest_imageName will be replaced with vendorController.vendor.value.v_banner.toString()

  • Related