Home > Back-end >  Null check operator used on null value on nullable list
Null check operator used on null value on nullable list

Time:06-16

I got below error in my flutter widget. addresses is nullable list and only got the index in that widget. May I know how can I solved this issue.

Null Check Operator used on null value

for this line

Address address = systemData.addresses![index];

address_title.dart

import 'package:auto_size_text/auto_size_text.dart';
import 'package:flutter/material.dart';
import 'package:thitsarparami/helper/constants.dart';
import 'package:thitsarparami/models/models.dart';

class AddressTile extends StatelessWidget {
  final SystemData systemData;
  final int index;
  const AddressTile({required this.systemData, required this.index, Key? key})
      : super(key: key);

  
  @override
  Widget build(BuildContext context) {
    Address address = systemData.addresses![index];
   

    return Container(
      padding: const EdgeInsets.symmetric(
        horizontal: 10,
      ),
      width: MediaQuery.of(context).size.width,
      margin: const EdgeInsets.only(bottom: 12, top: 12),
      child: Container(
        padding: const EdgeInsets.all(5),
        //  width: SizeConfig.screenWidth * 0.78,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(16),
            color: Theme.of(context).backgroundColor),
        child: Row(children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    const Icon(
                      Icons.location_pin,
                      //size: 30,
                    ),
                    const SizedBox(width: 4),
                    Flexible(
                      child: AutoSizeText(
                        address.line1Address!,
                        style: const TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(
                  height: 10,
                ),
                Container(
                  padding: const EdgeInsets.only(left: 20),
                  child: Column(
                    children: [
                      AutoSizeText(
                        '${address.line2Address!} ${address.township!} ${address.state!} ${address.country!} ${address.postalCode}',
                        //maxLines: 1,
                        style: const TextStyle(fontSize: 16),
                      ),
                    ],
                  ),
                ),
                const SizedBox(
                  height: 10,
                ),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    const Icon(
                      Icons.phone_outlined,
                      //size: 30,
                    ),
                    const SizedBox(width: 4),
                    Row(
                      children: [
                        //const SizedBox(height: 30),
                        TextButton(
                          style: TextButton.styleFrom(
                            textStyle: const TextStyle(fontSize: 16),
                          ),
                          onPressed: () {
                            launchURL("tel:${address.phone1!}");
                          },
                          child: Text(address.phone1!),
                        ),
                        const SizedBox(height: 10),
                        TextButton(
                          style: TextButton.styleFrom(
                            textStyle: const TextStyle(fontSize: 16),
                          ),
                          onPressed: () {
                            launchURL("tel:${address.phone2!}");
                          },
                          child: Text(address.phone2!),
                        ),
                      ],
                    )
                  ],
                ),
                Divider(
                  color: Theme.of(context).scaffoldBackgroundColor,
                  thickness: 2.0,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    TextButton.icon(
                      onPressed: () {
                        launchURL(systemData.facebook!);
                      },
                      icon: const Icon(Icons.facebook_outlined),
                      label: const AutoSizeText("Facebook"),
                    ),
                    TextButton.icon(
                      onPressed: () {
                        launchURL(systemData.messenger!);
                      },
                      icon: const Icon(Icons.messenger_outline_sharp),
                      label: const AutoSizeText("Chat"),
                    ),
                    TextButton.icon(
                      onPressed: () {
                        launchURL(systemData.youtube!);
                      },
                      icon: const Icon(Icons.videocam),
                      label: const AutoSizeText("Youtube"),
                    ),
                  ],
                )
              ],
            ),
          ),
        ]),
      ),
    );
  }
}

system_data.dart

import 'dart:convert';

import 'package:equatable/equatable.dart';

class YouTube extends Equatable {
  final String? videoId;
  final String? videoTitle;

  const YouTube({this.videoId, this.videoTitle});

  static YouTube fromJson(dynamic json) {
    return YouTube(
      videoId: json['video_id'],
      videoTitle: json['video_title'],
    );
  }

  static List<YouTube> youtubeFromJson(String str) =>
      List<YouTube>.from(json.decode(str).map((x) => YouTube.fromJson(x)));

  @override
  List<Object?> get props => [videoId];
}

class Address extends Equatable {
  final int id;
  final String? line1Address;
  final String? line2Address;
  final String? township;
  final String? state;
  final String? country;
  final String? postalCode;
  final String? phone1;
  final String? phone2;

  const Address({
    required this.id,
    this.line1Address,
    this.line2Address,
    this.township,
    this.state,
    this.country,
    this.postalCode,
    this.phone1,
    this.phone2,
  });

  static Address fromJson(dynamic json) {
    return Address(
      id: json['id'],
      line1Address: json['line1_address'],
      line2Address: json['line2_address'],
      township: json['township'],
      state: json['state'],
      country: json['country'],
      postalCode: json['postal_code'],
      phone1: json['phone1'],
      phone2: json['phone2'],
    );
  }

  static List<Address> addressesFromJson(String str) =>
      List<Address>.from(json.decode(str).map((x) => Address.fromJson(x)));

  @override
  List<Object?> get props => [id];
}

// ignore: must_be_immutable
class SystemData extends Equatable {
  String? biography;
  String? headMonkImageUrl;
  String? headMonkThumbnail;
  String? aboutThitsarparami;
  List<Address>? addresses;
  String? facebook;
  String? messenger;
  String? youtube;
  String? apk;
  String? fbShareMonk;
  String? fbShareAlbum;
  String? fbShareDhammaTalk;
  YouTube? youtubeLive;

  SystemData(
      {this.biography,
      this.headMonkImageUrl,
      this.headMonkThumbnail,
      this.aboutThitsarparami,
      this.addresses,
      this.facebook,
      this.messenger,
      this.youtube,
      this.apk,
      this.fbShareMonk,
      this.fbShareAlbum,
      this.fbShareDhammaTalk,
      this.youtubeLive});

  @override
  List<Object> get props => [biography!];

  static SystemData systemDataFromJson(List<dynamic> maps) {
    final SystemData about = SystemData();
    for (var element in maps) {
      if (element["code"] == "biography") about.biography = element["metadata"];
      if (element["code"] == "head_monk_image_url") {
        about.headMonkImageUrl = element["metadata"];
      }
      if (element["code"] == "head_monk_thumbnail") {
        about.headMonkThumbnail = element["metadata"];
      }
      if (element["code"] == "about_thitsarparami") {
        about.aboutThitsarparami = element["metadata"];
      }
      if (element["code"] == "facebook") about.facebook = element["metadata"];
      if (element["code"] == "messenger") about.messenger = element["metadata"];
      if (element["code"] == "youtube") about.youtube = element["metadata"];
      if (element["code"] == "apk") about.apk = element["metadata"];
      if (element["code"] == "fb_share_monk") {
        about.fbShareMonk = element["metadata"];
      }
      if (element["code"] == "fb_share_album") {
        about.fbShareAlbum = element["metadata"];
      }
      if (element["code"] == "fb_share_dhamma_talk") {
        about.fbShareDhammaTalk = element["metadata"];
      }
      if (element["code"] == "addresses") {
        about.addresses = Address.addressesFromJson(element["metadata"]);
      }
      if (element["code"] == "youtube_live") {
        about.youtubeLive = YouTube.youtubeFromJson(element["metadata"]).first;
      }
    }
    return about;
  }

  @override
  String toString() => 'About {id: $biography}';
}

CodePudding user response:

As you can see you have added ! for null-able addresses you can't do it since addresses can be null and address is not null. you can set either address to null-able like

Address? address = systemData.addresses![index]; or

assign if not null

if (systemData.addresses !=null){
Address address = systemData.addresses![index];
}

CodePudding user response:

Try using this class:

class AddressTile extends StatelessWidget {
  final SystemData systemData;
  final int index;
  const AddressTile({required this.systemData, required this.index, Key? key})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    if (systemData.addresses == null || systemData.addresses!.length < index) {
      return Container();
    }
    Address address = systemData.addresses![index];
    
    return Container(
      padding: const EdgeInsets.symmetric(
        horizontal: 10,
      ),
      width: MediaQuery.of(context).size.width,
      margin: const EdgeInsets.only(bottom: 12, top: 12),
      child: Container(
        padding: const EdgeInsets.all(5),
        //  width: SizeConfig.screenWidth * 0.78,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(16),
            color: Theme.of(context).backgroundColor),
        child: Row(children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    const Icon(
                      Icons.location_pin,
                      //size: 30,
                    ),
                    const SizedBox(width: 4),
                    Flexible(
                      child: AutoSizeText(
                        address.line1Address!,
                        style: const TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(
                  height: 10,
                ),
                Container(
                  padding: const EdgeInsets.only(left: 20),
                  child: Column(
                    children: [
                      AutoSizeText(
                        '${address.line2Address!} ${address.township!} ${address.state!} ${address.country!} ${address.postalCode}',
                        //maxLines: 1,
                        style: const TextStyle(fontSize: 16),
                      ),
                    ],
                  ),
                ),
                const SizedBox(
                  height: 10,
                ),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    const Icon(
                      Icons.phone_outlined,
                      //size: 30,
                    ),
                    const SizedBox(width: 4),
                    Row(
                      children: [
                        //const SizedBox(height: 30),
                        TextButton(
                          style: TextButton.styleFrom(
                            textStyle: const TextStyle(fontSize: 16),
                          ),
                          onPressed: () {
                            launchURL("tel:${address.phone1!}");
                          },
                          child: Text(address.phone1!),
                        ),
                        const SizedBox(height: 10),
                        TextButton(
                          style: TextButton.styleFrom(
                            textStyle: const TextStyle(fontSize: 16),
                          ),
                          onPressed: () {
                            launchURL("tel:${address.phone2!}");
                          },
                          child: Text(address.phone2!),
                        ),
                      ],
                    )
                  ],
                ),
                Divider(
                  color: Theme.of(context).scaffoldBackgroundColor,
                  thickness: 2.0,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    TextButton.icon(
                      onPressed: () {
                        launchURL(systemData.facebook!);
                      },
                      icon: const Icon(Icons.facebook_outlined),
                      label: const AutoSizeText("Facebook"),
                    ),
                    TextButton.icon(
                      onPressed: () {
                        launchURL(systemData.messenger!);
                      },
                      icon: const Icon(Icons.messenger_outline_sharp),
                      label: const AutoSizeText("Chat"),
                    ),
                    TextButton.icon(
                      onPressed: () {
                        launchURL(systemData.youtube!);
                      },
                      icon: const Icon(Icons.videocam),
                      label: const AutoSizeText("Youtube"),
                    ),
                  ],
                )
              ],
            ),
          ),
        ]),
      ),
    );
  }
}
  • Related