Home > Enterprise >  The method '[]' was called on null and the Null Aware Operators
The method '[]' was called on null and the Null Aware Operators

Time:07-26

I am working on a class which displays an image using a link in an xml file with the following code:

return HomePageCard(
        imageUrl: _newsData[key][i]['media\$content']['url'] ,
        ...

and

class HomePageCard extends StatelessWidget {
  final title,imageUrl,subtitle, time;

  const HomePageCard(
      {Key key, this.imageUrl, this.title, this.time, this.subtitle }): super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(top: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            height: 203,
            width: MediaQuery.of(context).size.width,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10),
              border: Border.all(
                color: const Color(0xff707070),
                width: 1,
              ),
              image: DecorationImage(image: NetworkImage(imageUrl), fit: BoxFit.fill),
            ),

           ...

however some links are missing and I get the following error:

The method '[]' was called on null.
Receiver: null
Tried calling: []("url")

To fix the problem I tried to use the "Null Aware Operators" like this:

 return HomePageCard(
                    imageUrl: _newsData[key][i]['media\$content']['url'] ?? 'https://i.f1g.fr/media/eidos/630x354_crop/2022/07/22/XVM75778610-09bb-11ed-8d4a-4a02bb9cc8b8.jpg',

but I still have the same error. Thanks for your help

CodePudding user response:

This happened because of 'media$content' is the one getting nulled, to try Null Aware Operators you must add '?' after ['media$content'], for example

_newsData[key][i]['media\$content']?['url'] ?? '...'

  • Related