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(() {});
}