Store Locally list with hive in flutter - flutter

The data of CategoryModel is storing in allCategory list. I want to store allCategory list locally with hive. How can I do? I tried many attempts but I could not. I also checked questions and answers on stack-overflow and many other websites, I did not get any answer which I wanted. I hope I explained well and you understood.
List<CategoryModel> allCategory =[];
allCategory.add(CategoryModel(/*all variables data*/));
class CategoryModel {
CategoryModel(
{required this.type,
this.iconData,
this.imageList,
this.notesText,
this.reminderIcon,
this.reminderText,
this.reminderTimeText,
this.titel,
this.color,
this.rawList,
this.reminderwidth,
this.backgroundImage,
this.reminderColor,
this.selectedTile,
this.selectedimage,
this.path,
this.crossCount,
this.duration,
this.colorSelected,
this.isSelected = false,
this.checkScreen = false,
this.notesController});
final CategoryType type;
String? titel;
IconData? iconData;
String? notesText;
List<File>? imageList;
IconData? reminderIcon;
String? reminderText;
String? reminderTimeText;
Color? color;
List<ListTileData>? rawList;
double? reminderwidth;
String? backgroundImage;
Color? reminderColor;
int? selectedTile;
int? selectedimage;
bool? checkScreen;
String? notesController;
int? crossCount;
String? path;
Duration? duration;
int? colorSelected;
bool? isSelected;
}

Related

Change the boolean value onclick and save to secured storage flutter

class Lessons {
final int? id;
final String? title;
final List<Resources> resources;
Lessons({
required this.id,
required this.title,
required this.resources,
});
}
class Resources extends Equatable {
final int? id;
final String? question;
final String? answer;
bool? bookmark;
Resources({
required this.id,
required this.question,
required this.answer,
required this.bookmark,
});
}
-these are my models, and have saved them using the secured storage flutter. How do i change just the bookmark and save it to secured storage?
i was able to change the bookmark but was unable to save it dynamically to secured storage.

How to use jsonSerialization with objectbox Entity class

I am facing issue when I am using JsonSerialization on Objectobox Entity
I tried to find better solution but I could not find
#JsonSerializable()
#Entity()
class ContactModel {
#Id()
int internalId;
#Index()
final String? id;
final String? userId;
final String? businessName;
final String? contactPersonName;
final String? contact;
final String? whatsappNumber;
final String? email;
final String? address;
final String? pinCode;
final String? city;
final String? businessType;
final String? description;
final String? img;
final String? lat;
final String? longitude;
final String? createDate;
final String? clientType;
ContactModel(
{this.internalId=0,
this.id,
this.userId,
this.businessName,
this.contactPersonName,
this.contact,
this.whatsappNumber,
this.email,
this.address,
this.city,
this.pinCode,
this.businessType,
this.description,
this.img,
this.lat,
this.longitude,
this.createDate,
this.clientType});
Map<String, dynamic> toMap(ContactModel contactModel) => _$ContactModelToJson(contactModel);
factory ContactModel.fromJson(Map<String, dynamic> json) => _$ContactModelFromJson(json);
}

Flutter correct data model

Since im new to flutter im not able to create a correct data model for my api data.
i got this dummy data at the moment:
List<Product> productsList = [
Product(
id: 1,
title: "Blue Bag",
price: 100,
description: " this is a description",
category: "Clothes",
image: "https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg",
rating: {rate: 2.1, count: 430}),];
i tried to create a model like this:
class Product {
final int? id;
final String? title;
final double? price;
final String? description;
final String? category;
final String? image;
final double? rate;
final int? count;
final Map<double, int>? rating;
Product({
this.id,
this.title,
this.price,
this.description,
this.category,
this.image,
this.rating,
this.rate,
this.count,
});
}
but the rating is wrong and rating: {rate: 2.1, count: 430} gives me an error.
Im used a little bit in typescript react when i can declare the reating type like
rating: {rate: number, count: number} . How can i do it in flutter?

The argument type 'List<Slots?>?' can't be assigned to the parameter type 'List<Slots>?'

i have recently migrated my code to null safety. got the below error in dart migrate command.
The argument type 'List<Slots?>?' can't be assigned to the parameter type 'List?' at lib/responsemodels/appointment/calendar/calendar_response.g.dart:17:5
Highlighted the error throwing line below
calendar_response.dart
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'calendar_response.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
CalenderResponse _$CalenderResponseFromJson(Map<String, dynamic> json) {
return CalenderResponse(
json['createdAt'] as String?,
json['dayInWeek'] as String?,
json['isHavingSlot'] as String?,
json['message'] as String?,
json['schedulerId'] as String?,
json['selectedDate'] as String?,
**(json['slotTimings'] as List?)
?.map(
(e) => e == null ? null : Slots.fromJson(e as Map<String, dynamic>))
?.toList(),**
json['status'] as String?,
json['updatedAt'] as String?,
json['currenttime'] as String?,
);
}
CalenderAvailableDatesResponse _$CalenderAvailableDatesResponseFromJson(
Map<String, dynamic> json) {
return CalenderAvailableDatesResponse(
(json['dateList'] as List?)?.map((e) => e as String).toList(),
json['message'] as String?,
json['status'] as String?,
json['currenttime'] as String?);
}
slots_response.dart
import 'package:json_annotation/json_annotation.dart';
part 'slots_response.g.dart';
#JsonSerializable(createToJson: false)
class SlotsResponse {
final String? status;
final String? message;
final List<SlotsGroups>? availableGroups;
SlotsResponse(this.availableGroups, this.message, this.status);
factory SlotsResponse.fromJson(Map<String, dynamic> map) =>
_$SlotsResponseFromJson(map);
}
#JsonSerializable(createToJson: false)
class SlotsGroups {
final String? groupId;
final String? vendorId;
final String? groupName;
final String? status;
final String? createdAt;
final String? updatedAt;
final List<Slots>? availSlots;
SlotsGroups(this.availSlots, this.createdAt, this.groupId, this.groupName,
this.status, this.updatedAt, this.vendorId);
factory SlotsGroups.fromJson(Map<String, dynamic> map) =>
_$SlotsGroupsFromJson(map);
}
#JsonSerializable(createToJson: false)
class Slots {
late final String? slotId;
late final String? startTime;
late final String? endTime;
late final String? duration;
late final String? startDateStrTime;
late final String? endDateStrTime;
late final String? stGivenString;
late final String? endGivenString;
late final String? status;
late final String? createdAt;
late final String? updatedAt;
late final String? isAnyAppointment;
late final BookingDetails? bookingDetails;
Slots(
this.createdAt,
this.duration,
this.endDateStrTime,
this.endGivenString,
this.endTime,
this.slotId,
this.stGivenString,
this.bookingDetails,
this.isAnyAppointment,
this.startDateStrTime,
this.startTime,
this.status,
this.updatedAt);
factory Slots.fromJson(Map<String, dynamic> map) => _$SlotsFromJson(map);
}
#JsonSerializable(createToJson: false)
class BookingDetails {
final String? customerName;
final String? serviceName;
BookingDetails(this.customerName, this.serviceName);
factory BookingDetails.fromJson(Map<String, dynamic> map) =>
_$BookingDetailsFromJson(map);
}
calendar_response.dart
import 'package:awomowa/responsemodels/appointment/slots/slots_response.dart';
import 'package:json_annotation/json_annotation.dart';
part 'calendar_response.g.dart';
#JsonSerializable(createToJson: false)
class CalenderResponse {
final String? status;
final String? message;
final String? isHavingSlot;
final String? schedulerId;
final String? dayInWeek;
final String? selectedDate;
final String? createdAt;
final String? updatedAt;
final List<Slots>? slotTimings;
final String? currenttime;
CalenderResponse(
this.createdAt,
this.dayInWeek,
this.isHavingSlot,
this.message,
this.schedulerId,
this.selectedDate,
this.slotTimings,
this.status,
this.updatedAt,
this.currenttime);
factory CalenderResponse.fromJson(Map<String, dynamic> map) =>
_$CalenderResponseFromJson(map);
}
#JsonSerializable(createToJson: false)
class CalenderAvailableDatesResponse {
final String? status;
final String? message;
final List<String>? dateList;
final String? currenttime;
CalenderAvailableDatesResponse(this.dateList, this.message, this.status,this.currenttime);
factory CalenderAvailableDatesResponse.fromJson(Map<String, dynamic> map) =>
_$CalenderAvailableDatesResponseFromJson(map);
}
The problem is that the function used in map can return null. In other words: its return type is Slots?, and not Slots.
To solve it you can filter the null values out of the list to turn the list from List<Slots?> to List<Slots> like this
(json['slotTimings'] as List?)
?.map(
(e) => e == null ? null : Slots.fromJson(e as Map<String, dynamic>))
.whereType<Slots>().toList(),
I presume you are using json_annotation, json_serializable with build_runner. As is being specified in the **.g file.
// GENERATED CODE - DO NOT MODIFY BY HAND
You should modify your model file to accommodate the issue/situation you have there and then and then run:
flutter pub run build_runner build
or
flutter pub run build_runner build --delete-conflicting-outputs

how to solve flutter null value issue in my code?

I want to keep null as a default value for product id, as it'll be later auto-generated, but I can't due to the flutter null safety check.
this is the instance creation code where I want to keep id = null:
var _editedProduct = Product(
id: null,
title: '',
price: 0,
description: '',
imageUrl: '',
);
and here is the code for my Product.dart file:
import 'package:flutter/material.dart';
class Product with ChangeNotifier {
final String id;
final String title;
final String description;
final double price;
final String imageUrl;
bool isFavorite;
Product({
required this.id,
required this.title,
required this.description,
required this.price,
required this.imageUrl,
this.isFavorite = false,
});
void toggleFavoriteStatus() {
isFavorite = !isFavorite;
notifyListeners();
}
}
A screenshot of the error
While you like to have id default value as null, First you need to accept nullable data. For final String id; will be final String? id; the default value can be provided on constructor by removing required to act as optional. id will have null by default.
To use id you need to check if it is null or not.
If you are sure it contains data use ! at the end like id!, or
provide a default value like id??"default", or
if(Product.id!=null){...}
class Product with ChangeNotifier {
final String? id;
final String title;
final String description;
final double price;
final String imageUrl;
bool isFavorite;
Product({
this.id,
required this.title,
required this.description,
required this.price,
required this.imageUrl,
this.isFavorite = false,
});
...
Learn more about null-safety
Following changes solved my issue:
changing final String id; to final String? id; in Product.dart
changing final productId = ModalRoute.of(context)!.settings.arguments as String; to final String? productId = ModalRoute.of(context)!.settings.arguments as String?;