Sort List<T> based on String DateTime - kotlin

I want to sort list descending based on UTC DateTime which is in String form.
My Class
data class CartEntity( val itemId: String, var itemName: String, var createdDate: String)
in this createdDate is "2020-07-28T14:28:52.877Z"
What I have tried
const val UTC_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
Collections.sort(list, object : Comparator<CartEntity> {
var f: DateFormat =
SimpleDateFormat(
AppConstants.UTC_FORMAT, Locale.ENGLISH
)
override fun compare(o1: CartEntity?, o2: CartEntity?): Int {
return try {
val firstitem = f.parse(o1?.createdDate!!)
val seconditem = f.parse(o2?.createdDate!!)
firstitem.compareTo(seconditem)
} catch (e: ParseException) {
throw IllegalArgumentException(e)
}
}
})
But still sort by descending is not working as expected

In kotlin style, you can use the standard library functions (following idioms):
Create a new sorted list out of the list you wanna sort:
fun main() {
val list = listOf<CartEntity>(
CartEntity(itemId = "", itemName = "", createdDate = "2020-07-28T14:28:52.877Z"),
CartEntity(itemId = "", itemName = "", createdDate = "2020-09-28T14:28:52.877Z"),
CartEntity(itemId = "", itemName = "", createdDate = "2020-08-28T14:28:52.877Z"),
CartEntity(itemId = "", itemName = "", createdDate = "2020-04-28T14:28:52.877Z"),
)
val format: DateFormat = SimpleDateFormat(AppConstants.UTC_FORMAT, Locale.ENGLISH)
val sortedList = list.sortedByDescending { format.parse(it.createdDate) }
println(sortedList) // `sortedList` is sorted out list, the `list` is holding the original order
}
Sort the original list (List should be mutable):
fun main() {
val list = mutableListOf<CartEntity>(
CartEntity(itemId = "", itemName = "", createdDate = "2020-07-28T14:28:52.877Z"),
CartEntity(itemId = "", itemName = "", createdDate = "2020-09-28T14:28:52.877Z"),
CartEntity(itemId = "", itemName = "", createdDate = "2020-08-28T14:28:52.877Z"),
CartEntity(itemId = "", itemName = "", createdDate = "2020-04-28T14:28:52.877Z"),
)
val format: DateFormat = SimpleDateFormat(AppConstants.UTC_FORMAT, Locale.ENGLISH)
list.sortByDescending { format.parse(it.createdDate) }
println(list) // `list` is sorted out list
}

This could be done using following approach.
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Tester {
static class Car {
private String date;
String getDate() {
return this.date;
}
void setDate(String date) {
this.date = date;
}
#Override
public String toString() {
return date;
}
// Imagine if you keep date not as strings
ZonedDateTime toDateTime(){
return ZonedDateTime.parse(this.date);
}
}
public static void main(String[] args) {
Car first = new Car();
first.setDate("2020-07-28T14:28:52.877Z");
Car second = new Car();
second.setDate("2010-07-28T14:28:52.877Z");
Car third = new Car();
third.setDate("2021-07-28T14:28:52.877Z");
List<Car> cars = Arrays.asList(first, second, third);
List<Car> sorted = cars.stream().sorted(Comparator.nullsLast(
(current, next) -> {
ZonedDateTime currentDate = ZonedDateTime.parse(current.getDate());
ZonedDateTime nextDate = ZonedDateTime.parse(next.getDate());
return nextDate.compareTo(currentDate);
})).collect(Collectors.toList());
}
}
If you keep the date as regular Date object it will be easier to work with them and the code above could be simplified a bit.
List<Car> sorted = cars.stream()
.sorted(Comparator.comparing(Car::toDateTime, Comparator.nullsLast(Comparator.reverseOrder())))
.collect(Collectors.toList());

Your code works pretty much fine #Charwaka.
data class CartEntity(val itemId: String, var itemName: String, var createdDate: String)
const val UTC_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
fun main() {
val list = mutableListOf<CartEntity>().apply {
add(CartEntity(itemId = "", itemName = "", createdDate = "2020-07-28T14:28:52.877Z"))
add(CartEntity(itemId = "", itemName = "", createdDate = "2020-09-28T14:28:52.877Z"))
add(CartEntity(itemId = "", itemName = "", createdDate = "2020-08-28T14:28:52.877Z"))
add(CartEntity(itemId = "", itemName = "", createdDate = "2020-04-28T14:28:52.877Z"))
}
Collections.sort(list, object : Comparator<CartEntity> {
var f: DateFormat = SimpleDateFormat(UTC_FORMAT, Locale.ENGLISH)
override fun compare(o1: CartEntity, o2: CartEntity): Int {
return try {
val firstitem = f.parse(o1.createdDate)
val seconditem = f.parse(o2.createdDate)
seconditem.compareTo(firstitem)
} catch (e: ParseException) {
throw IllegalArgumentException(e)
}
}
})
list
}
output:
CartEntity(itemId=, itemName=, createdDate=2020-09-28T14:28:52.877Z),
CartEntity(itemId=, itemName=, createdDate=2020-08-28T14:28:52.877Z),
CartEntity(itemId=, itemName=, createdDate=2020-07-28T14:28:52.877Z),
CartEntity(itemId=, itemName=, createdDate=2020-04-28T14:28:52.877Z)
code from #Animesh Sahu also works!
val format: DateFormat = SimpleDateFormat(AppConstants.UTC_FORMAT, Locale.ENGLISH)
list.sortByDescending { format.parse(it.createdDate) }

Related

null userId, Unhandled Exception: Null check operator used on a null value

I have an issue with userId in Habits table. it is a foreign key from id in Users Table. but I keep getting the error "Unhandled Exception: Null check operator used on a null value " from AddHabitDialogController class.
obviously userId should never be null. where is the issue? how can I solve it?
if more code is needed you can check : https://github.com/sarasoltan/habit_tracker
Users Table:
class UsersTable {
static const String tableName = 'Users';
static const String id = 'id';
static const String email = 'email';
static const String createQuery = '''
CREATE TABLE IF NOT EXISTS $tableName (
$id integer primary key autoincrement,
$email text not null unique);''';
#override
String toString() => 'Person, ID: $id, email: $email';
#override
bool operator ==(covariant Users other) => id == other.id;
#override
int get hashCode => id.hashCode;
}
Habits table:
class HabitsTable {
static const String tableName = 'Habits';
static const String id = 'id';
static const String userId = 'userId';
static const String text = 'text';
static const String emoji = 'emoji';
static const String period = 'period';
static const String startPeriod = 'startPeriod';
static const String createQuery = '''
CREATE TABLE IF NOT EXISTS $tableName (
$id integer primary key autoincrement,
$userId integer not null,
$text text not null,
$emoji text not null,
$period text not null,
$startPeriod integer,
FOREIGN Key($userId) REFERENCES ${UsersTable.tableName}(${UsersTable.id}));''';
User model class:
class Users {
late final int id;
late String email;
Users({
required this.id,
required this.email,
});
Users.fromDb(Map<String, dynamic> map) {
id = map[UsersTable.id];
email = map[UsersTable.email];
}
}
Habit model class:
class Habit {
late final int id;
late final int userId;
late String text;
late String emoji;
late final List<int> period;
late final DateTime? startPeriod;
Habit(
{
//required this.id,
required this.userId,
required this.text,
required this.emoji,
required this.period,
this.startPeriod});
Habit.fromDb(Map<String, dynamic> map) {
id = map[HabitsTable.id] as int;
userId = map[HabitsTable.userId] as int;
text = map[HabitsTable.text] as String;
emoji = map[HabitsTable.emoji];
period = (jsonDecode(map[HabitsTable.period]) as List<dynamic>)
.map((e) => e as int)
.toList();
if (map[HabitsTable.startPeriod] != null) {
startPeriod =
DateTime.fromMillisecondsSinceEpoch(map[HabitsTable.startPeriod]);
} else {
startPeriod = null;
}
}
Map<String, dynamic> toDb() {
Users? owner;
return {
//HabitsTable.id: id,
HabitsTable.userId: owner!.id,
HabitsTable.text: text,
HabitsTable.emoji: emoji,
HabitsTable.period: jsonEncode(period),
HabitsTable.startPeriod: startPeriod?.millisecondsSinceEpoch
};
}
AddHabitDialogController(error):
class AddHabitDialogController {
Users? owner;
//final user = FirebaseAuth.instance.currentUser;
//String get owneruserId => AuthService.firebase().currentUser!.id;
final List<bool> period = [true, true, true, true, true, true, true];
int? id;
int? userId;
String? emoji;
String? text;
StartPeriod startPeriod = StartPeriod.none;
final StreamController<bool> _addBtnEnabledCtrl = StreamController();
Stream<bool> get addBtnEnabled => _addBtnEnabledCtrl.stream;
final StreamController<StartPeriod> _selectedStartPeriodCtrl =
StreamController();
Stream<StartPeriod> get selectedStartPeriod =>
_selectedStartPeriodCtrl.stream;
final StreamController<bool> _loadingCtrl = StreamController();
Stream<bool> get loading => _loadingCtrl.stream;
void changePeriodValue(int index, bool newValue) {
period[index] = newValue;
_updateAddBtnEnabledState();
}
void changeTextValue(String newValue) {
text = newValue;
_updateAddBtnEnabledState();
}
void changeEmojiValue(String newEmoji) {
emoji = newEmoji;
_updateAddBtnEnabledState();
}
void changeStartPeriod(StartPeriod newValue) {
startPeriod = newValue;
_selectedStartPeriodCtrl.add(startPeriod);
}
Future<void> addHabit(BuildContext context) async {
_loadingCtrl.add(true);
final dataService = GetIt.I.get<DataService>();
final List<int> forPeriod = [];
for (int i = 0; i < period.length; i++) {
if (period[i]) {
forPeriod.add(i + 1);
}
}
final habit = Habit(
//id: id!,
userId: owner!.id, //error from here
emoji: emoji!,
text: text!,
period: forPeriod,
startPeriod: _calculateStartPeriodDateTime());
await dataService.addHabit(habit);
_loadingCtrl.add(false);
Navigator.of(context).pop();
}
void _updateAddBtnEnabledState() {
_addBtnEnabledCtrl.add((text?.isNotEmpty ?? false) &&
(emoji?.isNotEmpty ?? false) &&
period.where((e) => e).isNotEmpty);
}
DateTime? _calculateStartPeriodDateTime() {
final now = DateTime.now();
switch (startPeriod) {
case StartPeriod.today:
return DateTime(now.year, now.month, now.day);
case StartPeriod.thisMonth:
return DateTime(now.year, now.month);
case StartPeriod.thisYear:
return DateTime(now.year);
case StartPeriod.none:
default:
return null;
}
}
void dispose() {
_addBtnEnabledCtrl.close();
_loadingCtrl.close();
_selectedStartPeriodCtrl.close();
}
}
enum StartPeriod { none, today, thisMonth, thisYear }
Because the local variable of AddHabitDialogController owner can't be referenced before it is declared
class AddHabitDialogController {
Users? owner; // -> you did not assign this owner?

how use memorycache in this method?

how can i add memorycache in this method ?
this is a section of my code that i want to set memory cache on it.
public IActionResult Index(int pageId = 1, string filter = "",
int startPrice = 0, int endPrice = 0, string getType = "", string orderByType = "date",
List<int> selectedGroups = null, List<int> selectedBrand = null, List<int> selectedTags = null
, List<int> selectedsize = null , string Discount = "")
{
ViewBag.selectedGroups = selectedGroups;
ViewBag.selectedTags = selectedTags;
ViewBag.selectedsize = selectedsize;
ViewBag.Discount = Discount;
ViewBag.getType = getType;
ViewBag.Groups = _productService.GetAllGroup();
ViewBag.Tags = _productService.GetTags().Where(c => c.ActiveRow).ToList();
ViewBag.size = _productService.GetSizes().ToList();
ViewBag.pageId = pageId;
return View(_productService.GetProducttype(pageId, filter, startPrice, endPrice, getType, orderByType, selectedGroups, selectedBrand, 24, selectedTags, selectedsize, Discount));
}
private readonly IMemoryCache _memoryCache;
public Constructor (IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
public IActionResult Index(int pageId = 1, string filter = "",
int startPrice = 0, int endPrice = 0, string getType = "", string orderByType = "date",
List<int> selectedGroups = null, List<int> selectedBrand = null, List<int> selectedTags = null
, List<int> selectedsize = null , string Discount = "")
{
ViewBag.selectedGroups = selectedGroups;
ViewBag.selectedTags = selectedTags;
ViewBag.selectedsize = selectedsize;
ViewBag.Discount = Discount;
ViewBag.getType = getType;
var groups = new List<Group>();
if (_memoryCache.TryGetValue("groups", out groups)
{
ViewBag.Groups = groups;
}
else
{
groups = _productService.GetAllGroup();
_memoryCache.Set("groups", groups);
ViewBag.Groups = groups;
}
var tags = new List<Tag>();
if (_memoryCache.TryGetValue("tags", out tags)
{
ViewBag.Tags = tags;
}
else
{
tags = _productService.GetTags().Where(c => c.ActiveRow).ToList();
_memoryCache.Set("tags", tags);
ViewBag.Tags = tags;
}
var sizes = new List<Size>();
if (_memoryCache.TryGetValue("sizes", out sizes)
{
ViewBag.size = sizes;
}
else
{
sizes = _productService.GetSizes().ToList();
_memoryCache.Set("sizes", sizes);
ViewBag.size = sizes;
}
var pageId = null;
if (_memoryCache.TryGetValue("pageId", out pageId))
{
ViewBag.pageId = pageId;
}
else
{
_memoryCache.Set("pageId", pageId);
ViewBag.pageId = pageId;
}
return View(_productService.GetProducttype(pageId, filter, startPrice, endPrice, getType, orderByType, selectedGroups, selectedBrand, 24, selectedTags, selectedsize, Discount));
}

How do I assign a value to an empty string in my code to prevent NumberFormatException

I'm having a NumberFormatException which is likely due passing an empty string to product_quantity in the product and cart data class. I'm having difficulty assigning value to the product_quantity in my code before parsing it toInt()
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.hardextech.store, PID: 22948
java.lang.NumberFormatException: For input string: ""
at java.lang.Integer.parseInt(Integer.java:627)
at java.lang.Integer.parseInt(Integer.java:650)
at com.hardextech.store.ui.activities.ui.activities.CartListActivity.successfullyGetTheCartItemList(CartListActivity.kt:90)
at com.hardextech.store.firestore.FirestoreClass.getCartList$lambda-28(FirestoreClass.kt:493)
at com.hardextech.store.firestore.FirestoreClass.$r8$lambda$Uc6EU1OaDQc7HeKgs7cM5uEsC2A(Unknown Source:0)
at com.hardextech.store.firestore.FirestoreClass$$ExternalSyntheticLambda12.onSuccess(Unknown Source:4)
at com.google.android.gms.tasks.zzn.run(com.google.android.gms:play-services-tasks##17.2.0:4)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6819)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:497)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:912)
This is the successfullyGetCartTheCartItemList method referenced from the debugging console
fun successfullyGetTheCartItemList(listOfItemInTheCart: ArrayList<Cart>){
dismissProgressDialogue()
// checking for the product list in the stock-- determining if the product is available in the stock
for (everyProductInTheProductList in mProductList){
for (everyProductInTheCart in listOfItemInTheCart){
if (everyProductInTheProductList.product_id == everyProductInTheCart.product_id){
everyProductInTheCart.product_quantity = everyProductInTheProductList.product_quantity
// if there are no products in the stock
if (everyProductInTheProductList.product_quantity.toInt() == 0){
everyProductInTheCart.cart_quantity = everyProductInTheProductList.product_quantity
}
}
}
}
// initializing the mCartDataClassDetails
mCartDataClassDetails = listOfItemInTheCart
// checking for the product list in the cart
if (mCartDataClassDetails.size >0){
rv_cart_item_list.visibility = View.VISIBLE
ll_check_out.visibility = View.VISIBLE
tv_no_cart_item_found.visibility = View.GONE
rv_cart_item_list.layoutManager = LinearLayoutManager(this)
rv_cart_item_list.setHasFixedSize(true)
// create an adapter variable for the recycler view
val cartListAdapter = CartItemListAdapter(this, listOfItemInTheCart)
// pass the adapter to the recyclerview
rv_cart_item_list.adapter = cartListAdapter
// assign double to the sub-total in the itemListCart
var subTotal: Double = 0.0
// run through all product in the list
for (everyItemInTheCart in mCartDataClassDetails){
// checking for the available quantity of product
val availableProductQuantity = everyItemInTheCart.product_quantity.toInt()
if (availableProductQuantity > 0){
Log.i("Cart Title", everyItemInTheCart.product_title)
// convert the price to Double
val price = everyItemInTheCart.product_price.toDouble()
// convert the quantity to Int
val quantity = everyItemInTheCart.cart_quantity.toInt()
// calculate the sub-total cost
subTotal+=(price*quantity)
}
}
// assign the value of the sub total for each product sales
tv_product_subTotal.text = "NGN $subTotal"
// assigning the delivery cost for each product sales
// TODO: Seek for API to calculate the delivery cost for each product and/or write the code criteria for calculating it
tv_delivery_cost.text = (subTotal*0.05).toString()
if (subTotal > 0){
ll_check_out.visibility = View.VISIBLE
// TODO: Change the logic for the delivery cost
val totalProductCost = subTotal + (subTotal*0.05)
tv_total_product_cost.text = "NGN $totalProductCost"
} else{
ll_check_out.visibility = View.GONE
}
} else{
rv_cart_item_list.visibility = View.GONE
ll_check_out.visibility = View.GONE
tv_no_cart_item_found.visibility = View.VISIBLE
}
}
This is method from the Firestore class
fun getCartList(activity: Activity){
// the method for downloading the cart item list
mFireStore.collection(Constants.CART_ITEMS_COLLECTION)
// get the cart items for the logged in user
.whereEqualTo(Constants.USER_ID, getCurrentUserID())
.get()
.addOnSuccessListener { document->
Log.i(activity.javaClass.simpleName, document.documents.toString())
// get the list of the cart items--- number of products in the cart
val listOfCartItems: ArrayList<Cart> = ArrayList()
// run through each of the document(FireStore document field) in the list
for (loopingThroughCartItems in document.documents){
// converting the products in the cart to an object and surround with null check
val cartItemListObject = loopingThroughCartItems.toObject(Cart::class.java)!!
cartItemListObject.id= loopingThroughCartItems.id
// add the result of the loop to the cart item arrayList
listOfCartItems.add(cartItemListObject)
}
when(activity){
is CartListActivity->{
activity.successfullyGetTheCartItemList(listOfCartItems)
}
}
}.addOnFailureListener {e->
Log.e(activity.javaClass.simpleName, " Error downloading products in the cart", e)
when(activity){
is CartListActivity->{
activity.dismissProgressDialogue()
}
}
}
}
This is Product Data class
#Parcelize
data class Product(
val user_id: String = "",
var id: String = "",
val product_image: String = "",
val product_title: String = "",
val product_price: String = "",
val product_description: String = "",
val product_quantity: String = "",
val user_name: String = "",
var product_id:String =""
): Parcelable
This is the cart data class
#kotlinx.parcelize.Parcelize
data class Cart(
val user_id: String = "",
val product_id: String = "",
val product_title: String = "",
val product_image: String = "",
val product_price: String = "",
var cart_quantity: String = "",
var product_quantity: String ="",
var id: String = ""
): Parcelable
You can use toIntOrNull, which returns parsed Int or null when failed to parse. Then, use let with ?., like this:
string.toIntOrNull()?.let { parsedInt ->
// Your code here
}

SwiftUI : Type of expression is ambiguous without more context when define data type

This warning is really weird to me because I was able to create one of the data type but the other 2 are not. You will see the implement + init are mostly the same.
1 small question, if my graphql API does not have id, which is the best way to implement the id? I'm currently use country name for id. which I think is a pretty bad practice
Thank you in advance!
typealias CountryData = ScpecificCountryQuery.Data
struct Countries: Decodable {
var countries: [Country]
init(_ countries: CountryData?) {
self.countries = countries?.countries.map({ country -> Country in
Country(country)
}) ?? []
}
struct Country: Identifiable, Decodable {
var id: String {
return currency
}
var code: String
var name: String
var phone: String
var capital: String
var currency : String
var continent: Continent ( Does not have any warning)
var languages : Lan ("Type of expression is ambiguous without more context")
var states: State ("Type of expression is ambiguous without more context")
init(_ country: ScpecificCountryQuery.Data.Country?) {
self.name = country?.name ?? ""
self.code = country?.code ?? ""
self.phone = country?.phone ?? ""
self.capital = country?.capital ?? ""
self.currency = country?.currency ?? ""
self.emoji = country?.emoji ?? ""
self.continent = Continent(country?.continent)
self.languages = Lan(country?.languages)
self.states = State(country?.states)
}
struct Lan: Decodable {
var code: String
var name: String
init(_ lan: ScpecificCountryQuery.Data.Country.Language?) {
self.code = lan?.code ?? ""
self.name = lan?.name ?? ""
}
}
struct Continent: Decodable {
var code: String
var name: String
init (_ continent: ScpecificCountryQuery.Data.Country.Continent?) {
self.code = continent?.code ?? ""
self.name = continent?.name ?? ""
}
}
struct State {
var code: String
var name: String
init (_ state: ScpecificCountryQuery.Data.Country.State?) {
self.code = state?.code ?? ""
self.name = state?.name ?? ""
}
}
}
}

NoSuchMethodError : The Setter "movies=" was called on null

Future<YifyMovies> getData() async {
var res = await http.get("https://yts.lt/api/v2/list_movies.json");
var decodedJson = jsonDecode(res.body);
YifyMovies movie = YifyMovies();
movie.data.movies = [];
for (var json in decodedJson) {
movie.data.movies.add(Movies.fromJson(json));
}
return movie;
}
Yify Movies class:-
It's the JSON from the above API converted int0 dart.
class YifyMovies {
String status;
String statusMessage;
Data data;
YifyMovies({this.status, this.statusMessage, this.data});
YifyMovies.fromJson(Map<String, dynamic> json) {
status = json['status'];
statusMessage = json['status_message'];
data = json['data'] != null ? new Data.fromJson(json['data']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
data['status_message'] = this.statusMessage;
if (this.data != null) {
data['data'] = this.data.toJson();
}
return data;
}
}
class Data {
int movieCount;
int limit;
int pageNumber;
List<Movies> movies;
Data({this.movieCount, this.limit, this.pageNumber, this.movies});
Data.fromJson(Map<String, dynamic> json) {
movieCount = json['movie_count'];
limit = json['limit'];
pageNumber = json['page_number'];
if (json['movies'] != null) {
movies = new List<Movies>();
json['movies'].forEach((v) {
movies.add(new Movies.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['movie_count'] = this.movieCount;
data['limit'] = this.limit;
data['page_number'] = this.pageNumber;
if (this.movies != null) {
data['movies'] = this.movies.map((v) => v.toJson()).toList();
}
return data;
}
}
class Movies {
int id;
String url;
String imdbCode;
String title;
String titleEnglish;
String titleLong;
String slug;
int year;
double rating;
int runtime;
List<String> genres;
String summary;
String descriptionFull;
String synopsis;
String ytTrailerCode;
String language;
String mpaRating;
String backgroundImage;
String backgroundImageOriginal;
String smallCoverImage;
String mediumCoverImage;
String largeCoverImage;
String state;
List<Torrents> torrents;
String dateUploaded;
int dateUploadedUnix;
Movies(
{this.id,
this.url,
this.imdbCode,
this.title,
this.titleEnglish,
this.titleLong,
this.slug,
this.year,
this.rating,
this.runtime,
this.genres,
this.summary,
this.descriptionFull,
this.synopsis,
this.ytTrailerCode,
this.language,
this.mpaRating,
this.backgroundImage,
this.backgroundImageOriginal,
this.smallCoverImage,
this.mediumCoverImage,
this.largeCoverImage,
this.state,
this.torrents,
this.dateUploaded,
this.dateUploadedUnix});
Movies.fromJson(Map<String, dynamic> json) {
id = json['id'];
url = json['url'];
imdbCode = json['imdb_code'];
title = json['title'];
titleEnglish = json['title_english'];
titleLong = json['title_long'];
slug = json['slug'];
year = json['year'];
rating = json['rating'];
runtime = json['runtime'];
genres = json['genres'].cast<String>();
summary = json['summary'];
descriptionFull = json['description_full'];
synopsis = json['synopsis'];
ytTrailerCode = json['yt_trailer_code'];
language = json['language'];
mpaRating = json['mpa_rating'];
backgroundImage = json['background_image'];
backgroundImageOriginal = json['background_image_original'];
smallCoverImage = json['small_cover_image'];
mediumCoverImage = json['medium_cover_image'];
largeCoverImage = json['large_cover_image'];
state = json['state'];
if (json['torrents'] != null) {
torrents = new List<Torrents>();
json['torrents'].forEach((v) {
torrents.add(new Torrents.fromJson(v));
});
}
dateUploaded = json['date_uploaded'];
dateUploadedUnix = json['date_uploaded_unix'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['url'] = this.url;
data['imdb_code'] = this.imdbCode;
data['title'] = this.title;
data['title_english'] = this.titleEnglish;
data['title_long'] = this.titleLong;
data['slug'] = this.slug;
data['year'] = this.year;
data['rating'] = this.rating;
data['runtime'] = this.runtime;
data['genres'] = this.genres;
data['summary'] = this.summary;
data['description_full'] = this.descriptionFull;
data['synopsis'] = this.synopsis;
data['yt_trailer_code'] = this.ytTrailerCode;
data['language'] = this.language;
data['mpa_rating'] = this.mpaRating;
data['background_image'] = this.backgroundImage;
data['background_image_original'] = this.backgroundImageOriginal;
data['small_cover_image'] = this.smallCoverImage;
data['medium_cover_image'] = this.mediumCoverImage;
data['large_cover_image'] = this.largeCoverImage;
data['state'] = this.state;
if (this.torrents != null) {
data['torrents'] = this.torrents.map((v) => v.toJson()).toList();
}
data['date_uploaded'] = this.dateUploaded;
data['date_uploaded_unix'] = this.dateUploadedUnix;
return data;
}
}
class Torrents {
String url;
String hash;
String quality;
String type;
int seeds;
int peers;
String size;
int sizeBytes;
String dateUploaded;
int dateUploadedUnix;
Torrents(
{this.url,
this.hash,
this.quality,
this.type,
this.seeds,
this.peers,
this.size,
this.sizeBytes,
this.dateUploaded,
this.dateUploadedUnix});
Torrents.fromJson(Map<String, dynamic> json) {
url = json['url'];
hash = json['hash'];
quality = json['quality'];
type = json['type'];
seeds = json['seeds'];
peers = json['peers'];
size = json['size'];
sizeBytes = json['size_bytes'];
dateUploaded = json['date_uploaded'];
dateUploadedUnix = json['date_uploaded_unix'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['url'] = this.url;
data['hash'] = this.hash;
data['quality'] = this.quality;
data['type'] = this.type;
data['seeds'] = this.seeds;
data['peers'] = this.peers;
data['size'] = this.size;
data['size_bytes'] = this.sizeBytes;
data['date_uploaded'] = this.dateUploaded;
data['date_uploaded_unix'] = this.dateUploadedUnix;
return data;
}
}
Any help, please? Tell me if any more info is required?
I'm trying to list all the movies and use them for tabview in flutter which can show them in listview as well as gridview. I'm using Bloc architecture for layouts so YifyMovie class is in hom_model and the code above is in home_provider.
Your YifyMovies class is already handling the parsing for you.
So your code should change from
Future<YifyMovies> getData() async {
var res = await http.get("https://yts.lt/api/v2/list_movies.json");
var decodedJson = jsonDecode(res.body);
YifyMovies movie = YifyMovies();
movie.data.movies = [];
for (var json in decodedJson) {
movie.data.movies.add(Movies.fromJson(json));
}
return movie;
}
to
Future<YifyMovies> getData() async {
var res = await http.get("https://yts.lt/api/v2/list_movies.json");
var decodedJson = jsonDecode(res.body);
YifyMovies movie = YifyMovies.fromJson(decodedJson);
return movie;
}