Home > database >  The method '[]' was called on null. Receiver: null in Flutter
The method '[]' was called on null. Receiver: null in Flutter

Time:10-23

Where do I wrong? I created this method, I get no issue in debugger, but when I run the app I get this error. The following NoSuchMethodError was thrown building: The method '[]' was called on null. Receiver: null Tried calling: How can I solve this issue?

enter image description here

late String urlImage;
  late String urlImageSource;
  var _post;

  final List<Article> _posts = [
    Article(
      urlImage: 'urlImage',
      urlImageSource: 'urlImageSource',
      title: 'title',
      description: 'description',
    ),
  ];

  String checkIfUrlContainPrefixHttps(String urlImageSource) {
    if (!urlImageSource.startsWith("//") || !urlImageSource.startsWith("http")) {
      return  urlImageSource;
    } else {
      return 'https://'   urlImageSource;
    }
  }

Widget image

SizedBox(
         height: 190,
         width: double.infinity,
         child: CachedNetworkImage(
           imageUrl: checkIfUrlContainPrefixHttps(_post[0].urlImageSource),
           fit: BoxFit.cover,
           placeholder: (context, url) => Image.asset("assets/gif/shimmer.gif",
           width: double.infinity,
           height: 190,
           fit: BoxFit.cover,
         ),
         errorWidget: (context, url, error) => 
             Image.asset("assets/images/unloadedImage.png", 
              width: 250, 
              height: 250,
      ),
   ),
)

CodePudding user response:

Your _post is null and you are trying to get 0 item in it, try this:

checkIfUrlContainPrefixHttps(_post != null ? _post[0].urlImageSource :'')
  • Related