Kuldeep
Kuldeep

Reputation: 141

How to resolve non-nullable error in Flutter?

I'm new to flutter development and I'm trying to implement a category page where the data will load from a json file. But I'm getting null safety error"The non-nullable variable 'categories' must be initialized. Try adding an initializer expression." while creating the class. Please find the below codes for your reference and help to resolve.

There are two dart files one is category_models.dart and another is homecategories.dart

Thanks in advance.

Category_model.dart

    import 'dart:convert';

    class CategoryModel { 
    static List<Category> categories;
    }

    class Category {
    final int id;
    final String name;
    final String image;
    Category({
    required this.id,
    required this.name,
    required this.image,
    });

    Category copyWith({
    int? id,
    String? name,
    String? image,
    }) {
    return Category(
      id: id ?? this.id,
      name: name ?? this.name,
      image: image ?? this.image,
    );
    }

    Map<String, dynamic> toMap() {
    return {
      'id': id,
      'name': name,
      'image': image,
    };
    }

    factory Category.fromMap(Map<String, dynamic> map) {
    return Category(
      id: map['id'],
      name: map['name'],
      image: map['image'],
    );
    }

    String toJson() => json.encode(toMap());

    factory Category.fromJson(String source) =>
      Category.fromMap(json.decode(source));

    @override
    String toString() => 'Category(id: $id, name: $name, image: $image)';

    @override
    bool operator ==(Object other) {
    if (identical(this, other)) return true;

    return other is Category &&
        other.id == id &&
        other.name == name &&
        other.image == image;
    }

    @override
    int get hashCode => id.hashCode ^ name.hashCode ^ image.hashCode;
    }

Categoroes.dart

    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    import 'dart:convert';
    import 'package:citimart/models/category_model.dart';

    class HomeCategories extends StatefulWidget {
    @override
    _HomeCategoriesState createState() => _HomeCategoriesState();
    }

    class _HomeCategoriesState extends State<HomeCategories> {
    void initState() {
    super.initState();
    loadData();
    }

    loadData() async {
    await Future.delayed(Duration(seconds: 2));
    final categoryJson =
        await rootBundle.loadString("assets/files/categories.json");
    final decodedData = jsonDecode(categoryJson);
    var categoriesData = decodedData["categories"];
    CategoryModel.categories = List.from(categoriesData)
        .map<Category>((category) => Category.fromMap(category))
        .toList();
    setState(() {});
    }

Upvotes: 2

Views: 2232

Answers (2)

Naslausky
Naslausky

Reputation: 3768

Your variable static List<Category> categories; is a List<Category> type. Since its non-nullable, the value it holds can never be null. So from the initialization you need to supply a value.

You can solve this in a few ways. The easiest would be to give an initial value:

static List<Category> categories = [];

Other ways to handle this without giving an initial value would be to make the variable nullable, or marking it with a late initialization keyword. To read more of this, check the oficial documentation here.

Upvotes: 2

Rohan Thacker
Rohan Thacker

Reputation: 6337

You must initialize the CategoryModel.categories variable, since this variable has been defined as a non-nullable it cant be left uninitialized as this is null.

You should update the model class and set an initial value for the categories, for example

class CategoryModel { 
    static List<Category> categories = List.empty();
}

Upvotes: 2

Related Questions