I need to make a cart page for an e-commerce app. where I am getting JSON data from API. I can fetch the data and show data. but when it's matter to cart I cannot add this data to my provider page.
This is MY Provider Page For Album
import 'package:flutter/material.dart';
import 'package:provider_test/albumModel.dart';
import '../Service/service.dart';
class MyStore extends ChangeNotifier {
List<Album> _albums = [];
List<Album> _busket = [];
Album _activeAlbum = null;
List<Album> get albums => _albums;
List<Album> get buskets => _busket;
Album get activeAlbum => _activeAlbum;
}
And this is my Album Model Page:
import 'dart:convert';
import 'package:flutter/cupertino.dart';
List<Album> allalbumsFromJson(String str) {
final jsonData = json.decode(str);
return new List<Album>.from(jsonData.map((x) => Album.fromJson(x)));
} //ef
class AlbumList with ChangeNotifier {
final List<Album> albums;
AlbumList({
this.albums,
});
factory AlbumList.fromJson(List<dynamic> parsedJson) {
List<Album> albums = List<Album>();
albums = parsedJson.map((i) => Album.fromJson(i)).toList();
return AlbumList(albums: albums);
}
notifyListeners();
} //ef
class Album with ChangeNotifier {
int userId;
int id;
String title;
Album({this.userId, this.id, this.title});
Album.fromJson(Map<String, dynamic> json) {
userId = json['userId'];
id = json['id'];
title = json['title'];
}
notifyListeners();
} //ef
Album albumFromJson(String str) {
final jsonData = json.decode(str);
return Album.fromJson(jsonData);
} //ef
Now I can fetch Data Using this Function:
import 'package:flutter/cupertino.dart';
import 'package:provider_test/albumModel.dart';
import 'package:http/http.dart' as HTTP;
final url = ('https://jsonplaceholder.typicode.com/albums');
Future<List<Album>> getAllAlbum() async {
final response = await http.get(url);
// print(response.body);
return allalbumsFromJson(response.body);
}
Future<Album> getAlbum() async {
final response = await http.get('$url/1');
return albumFromJson(response.body);
}
How Can I insert getAllAlbums() Data or you can say List Data into the _albums=[] which is situated in Mystore Page?
Hi for the cart I think you the best way you must use a map instead of a list like below:
Map<int, FavoriteModel> _favoites = {};
Map<int, FavoriteModel> get favoitesItem {
return _favoites;
}
And for adding data from you can use of this method:
void addOrRemoveSingleItem({
int foodId,
String title,
double price,
String imageUrl,
int userId
}) async {
if (_favoites.containsKey(foodId)) {
try {
final res = await http.post(
addFavoriteUrl,
body: {
"user_id": userId.toString(),
"food_id": foodId.toString(),
"Is_delete": "1",
},
);
} catch (e) {
print(e);
throw (e);
}
} else {
try {
_favoites.putIfAbsent(
foodId,
() => FavoriteModel(
id: foodId,
name: title,
regularPrice: price,
featureImage: imageUrl,
),
);
http.post(
addFavoriteUrl,
body: {
"user_id": userId.toString(),
"food_id": foodId.toString(),
},
);
} catch (e) {
print(e);
throw (e);
}
}
notifyListeners();
}