The argument type 'int?' can't be assigned to the parameter type 'int'

Viewed 39

this is RadioModel.dart I am a beginner in flutter and I want to display my JSON file data on vx swipper.builder but i don't know whats going on here when i pass item count i face this error i know i am doing something wrong and i can't fix this I am a beginner in flutter and I want to display my JSON file data on vx swipper.builder but i don't know whats going on here when i pass item count i face this error i know i am doing something wrong and i can't fix this I am a beginner in flutter and I want to display my JSON file data on vx swipper.builder but i don't know whats going on here when i pass item count i face this error i know i am doing something wrong and i can't fix this

import 'dart:convert';

class MyRadioList {
  static List<MyRadio>? radios;

  // Get Item by ID
  MyRadio getById(int id) =>
      radios!.firstWhere((element) => element.id == id, orElse: null);

  // Get Item by position
  MyRadio getByPosition(int pos) => radios![pos];
}

class MyRadio {
  final int id;
  final int order;
  final String name;
  final String tagline;
  final String color;
  final String desc;
  final String url;
  final String category;
  final String icon;
  final String image;
  final String lang;
  MyRadio({
    required this.id,
    required this.order,
    required this.name,
    required this.tagline,
    required this.color,
    required this.desc,
    required this.url,
    required this.category,
    required this.icon,
    required this.image,
    required this.lang,
  });

  factory MyRadio.fromMap(Map<String, dynamic> map) {
    return MyRadio(
      id: map['id'],
      order: map['order'],
      name: map['name'],
      tagline: map['tagline'],
      color: map['color'],
      desc: map['desc'],
      url: map['url'],
      category: map['category'],
      icon: map['icon'],
      image: map['image'],
      lang: map['lang'],
    );
  }

  toMap() => {
        "id": id,
        "order": order,
        "name": name,
        "tagline": tagline,
        "color": color,
        "desc": desc,
        "url": url,
        "category": category,
        "icon": icon,
        "image": image,
        "lang": lang,
      };
}

// this is HomePage.dart

import 'dart:convert';
import 'dart:ffi';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_application_1/models/RadioModel.dart';
import 'package:flutter_application_1/utils/Ai_Utils.dart';
import 'package:velocity_x/velocity_x.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  //get daata from radio model
  @override
  void initstate() {
    super.initState();
    fetchradios();
  }

  fetchradios() async {
    final radioJson = await rootBundle.loadString("assets/radio.json");
    final decodedData = jsonDecode(radioJson);
    MyRadioList.radios = List.from(decodedData)
        .map<MyRadio>(((radio) => MyRadio.fromMap(radio)))
        .toList();
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      drawer: Drawer(),
      body: Stack(children: [
        VxAnimatedBox()
            .withGradient(LinearGradient(
              colors: [AiColors.primaryColor1, AiColors.primaryColor2],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
            ))
            .size(context.screenWidth, context.screenHeight)
            .make(),
        AppBar(
          title: "AI Radio".text.xl4.bold.white.make().shimmer(
              primaryColor: Vx.purple300, secondaryColor: Colors.white),
          elevation: 0.0,
          backgroundColor: Colors.transparent,
          centerTitle: true,
        ).h(100.0).p16(),
        VxSwiper.builder(
            itemCount: MyRadioList.radios?.length,      // error line
            itemBuilder: (context, index) {
              final rad = MyRadioList.radios![index];
              return VxBox(child: ZStack([]))
                  .bgImage(DecorationImage(image: NetworkImage(rad.image)))
                  .make();
            })
      ]),
    );
  }
}
1 Answers

itemCount must be a non-nullable int.

But your static List<MyRadio>? radios is a nullable List, so the length may be null if the List is never initialized

You can use the If-null operator ?? to initialize it to 0 or whatever default value you want to use if the length happens to be null

Change this line:

itemCount: MyRadioList.radios?.length,      // error line

To this:

itemCount: MyRadioList.radios?.length ?? 0    // 0 or whatever default value

The line above essentially reads if MyRadioList.radios?.length is not null, then use it, otherwise set MyRadioList.radios?.length to 0.

Using ?? ensures that the length of your list will never be null

Related