How to display a single Item from an array of objects - flutter - flutter

Hello I need help with a question that's a little tricky. I have an array of objects below. These objects are gotten as a results of a get http request I made to an endpoint. The endpoint requires some Ids and those Ids are also returned in the response objects which are: anchorOid, providerOid, and StateOid. So before this response a user will select an anchor, state and provider then it make request to the end point and return the users Stocks object which is the object below. So whatever the user selects before the http request, those are the IDs that would be returned in the response. So my challenge is after getting the response, before I loop through the whole objects and display them using datatable row and column, how can I display just the anchor, State, before iterating over the whole object just to show the user that this is the anchor and state you selected since the anchor and state are the same in all the objects hence the originate from the users selection. How can can do that please?
_getStocksByProviderIdByAnchorIdBySeasonId() async {
try {
_prefs = await SharedPreferences.getInstance();
var _stockService = StockService();
var result =
await _stockService.getStocksByProviderIdByAnchorIdBySeasonId(
_prefs.getInt('providerOid'),
widget.anchorOid,
widget.seasonOid,
widget.stateOid);
var stocks = await json.decode(result.body);
_stocks = <Stock>[];
stocks.forEach((stock) {
var _stock = Stock();
_stock.oid = stock['oid'];
_stock.date = DateTime.parse(stock['date']);
_stock.anchor = stock['anchor'];
_stock.state = stock['state'];
setState(() {
_stocks.add(_stock);
});
});
print("Stocks");
print(stocks);
setState(() {
data = stocks;
_isLoading = false;
});
} catch (e) {
setState(() {
_isLoading = false;
});
return e.toString();
}
}
I tried to do this:
stocks[0]['anchor]
but its only picking the first index so how do I make the index dynamic I don't know what to do.
[
{
"oid": 3,
"anchor": "MAIZE ASSOCIATION OF NIGERIA",
"anchorOid": 1,
"date": "2021-07-09T14:37:00.403",
"provider": "ERG Agro Solutions",
"providerOid": 1,
"season": "WET SEASON - 2020",
"seasonOid": 1,
"stateOid": 1,
"state": "Abia",
"stockItems": [],
"totalStockItems": 0
},
{
"oid": 4,
"anchor": "MAIZE ASSOCIATION OF NIGERIA",
"anchorOid": 1,
"date": "2021-08-09T14:39:00.403",
"provider": "ERG Agro Solutions",
"providerOid": 1,
"season": "WET SEASON - 2020",
"seasonOid": 1,
"stateOid": 1,
"state": "Abia",
"stockItems": [],
"totalStockItems": 0
}
]

You can try the first method on List like this,
void main() {
List data = [
{
"oid": 3,
"anchor": "MAIZE ASSOCIATION OF NIGERIA",
"anchorOid": 1,
"date": "2021-07-09T14:37:00.403",
"provider": "ERG Agro Solutions",
"providerOid": 1,
"season": "WET SEASON - 2020",
"seasonOid": 1,
"stateOid": 1,
"state": "Abia",
"stockItems": [],
"totalStockItems": 0
},
{
"oid": 4,
"anchor": "MAIZE ASSOCIATION OF NIGERIA",
"anchorOid": 1,
"date": "2021-08-09T14:39:00.403",
"provider": "ERG Agro Solutions",
"providerOid": 1,
"season": "WET SEASON - 2020",
"seasonOid": 1,
"stateOid": 1,
"state": "Abia",
"stockItems": [],
"totalStockItems": 0
}
];
print(data.first['anchor']);
}
It will always pick the first element of an array.

Related

Flutter : How change modify unmodifiable map

I have list like this in provider:
List orders=[]:
void getOrders(){
orders = [
{"id":1,
"order":[
{"id":1,"name":"mike"},
{"id":2,"name":"john"},
{"id":3,"name":"smith"}
]
},
{"id":1,
"order":[
{"id":1,"name":"roz"},
{"id":2,"name":"sam"},
{"id":3,"name":"ruby"}
]
},
];
notifyListeners();
}
in provider when I use this methos to chane indexed order with another:
void changeOrder(orderIndex,item){
orders[orderIndex].update("order",(val)=>item);
notifyListeners();
}
I get this error type '(dynamic) => dynamic' is not a subtype of type '(Object) => Object' of 'update'
and when I use this :
void changeOrder(orderIndex,item){
orders[orderIndex]["order"]=item;
notifyListeners();
}
I get this error Unsupported operation: Cannot modify unmodifiable map
Add More Details
the item in changeOrder method comes from screen contain orders :
var item = List.from(orders[index]);
orders type is List<Map<String, dynamic>>. While reading the item, it will be a map instead of list.
Map item = Map.from(orders[index]);
And you can use both way you;ve tried.
List<Map<String, dynamic>> orders = [];
void getOrders() {
orders = [
{
"id": 1,
"order": [
{"id": 1, "name": "mike"},
{"id": 2, "name": "john"},
{"id": 3, "name": "smith"}
]
},
{
"id": 1,
"order": [
{"id": 1, "name": "roz"},
{"id": 2, "name": "sam"},
{"id": 3, "name": "ruby"}
]
},
];
}
void changeOrder(orderIndex, item) {
orders[orderIndex]["order"] = item;
// orders[orderIndex].update("order", (val) => item);
}
void main(List<String> args) {
getOrders();
print(orders);
Map item = Map.from(orders[1]);
changeOrder(1, item);
print(orders);
}

Add json values in to the list of object

How I can get all the values in this JSON and add all the value in to the list of object in the dart?
"data": [
{
"$id": "2",
"serviceId": 1017,
"name": "اکو",
"code": "235",
"price": 1562500,
"isDefault": true,
"transportCostIncluded": false,
"qty": 0,
"minQty": 1,
"maxQty": 2,
"description": "یک دستگاه اکو به همراه دو باند و یک عدد میکروفن (تامین برق بعهده پیمانکار می باشد).",
"contractorSharePercent": 65,
"unitMeasureId": 7,
"unitMeasureName": "هر 60 دقیقه",
"superContractorsId": null
},
],
like this var list = ["2",1017,....]
Assuming you've a JSON file, which you may have parsed like this:
String json = await rootBundle.loadString('file_name.json');
var response = jsonDecode(json);
This is how you can do it:
List<dynamic> jsonData; //similar to var jsonData = [something, something, ...]
//traversing through each value in the key value arrangement of the json
for (var k in response.values) {
jsonData.add(k); //adding each value to the list
}
After the loop ends, jsonData will have all the values of your JSON file.
It's important for you to know that even if you put the keys on a list, they won't necessarily be in order, because of the way maps work.
Assuming your json is a map and not a json string, you could put all of the values on a list like so:
var myList = (jsonObject['data'] as List).fold<List>(
[],
(prev, curr) => [...prev, ...curr.values]
);
if you were talking about a json string:
Map<String, dynamic> jsonObject = jsonDecode(jsonString);
For simplicity, lets assume this json is unparsed in a string.
(1) Assuming the code snippet you added is a string && is valid json you can do as follows :)
import 'dart:convert';
void main() {
var x = json.decode('''
{
"data": [
{
"hello": "2",
"serviceId": 1017,
"name": "اکو",
"code": "235",
"price": 1562500,
"isDefault": true,
"transportCostIncluded": false,
"qty": 0,
"minQty": 1,
"maxQty": 2,
"description": "یک دستگاه اکو به همراه دو باند و یک عدد میکروفن (تامین برق بعهده پیمانکار می باشد).",
"contractorSharePercent": 65,
"unitMeasureId": 7,
"unitMeasureName": "هر 60 دقیقه",
"superContractorsId": null
}
]
}
''');
print(x);
List<dynamic> listOfObjects = (x['data'] as Iterable<dynamic>).toList();
/// this is just gonna be a list of all of your object.
print(listOfObjects);
List<dynamic> listOfValues = (x['data'] as Iterable<dynamic>).map((_object) {
return (_object as Map<String, dynamic>).values.toList();
}).toList();
/// this is gonna be a 2d array here,
print(listOfValues);
}
Hope This helped out:)
Also json here comes from import 'dart:convert';

Converting list of map to a list of objects in dart

I am making a request to an API which returns me a response.
final response = await http.get(Uri.parse(requestUrl), headers: headers);
It returns the following response.
{
"meta": {
"upcomingMatchCount": 5,
"inProgressMatchCount": 10,
"completedMatchCount": 5
},
"matchList": {
"matches": [
{
"id": 49944,
"matchTypeId": 15,
"series": {
"id": 2739,
"name": "LV= Insurance County Championship 2021",
"shortName": "LV= Insurance County Championship 2021"
},
"name": "",
"status": "LIVE",
"venue": {
"name": "The Cooper Associates County Ground",
"shortName": "The Cooper Associates County Ground"
},
"homeTeam": {
"isBatting": true,
"id": 55,
"name": "Somerset",
"shortName": "SOM"
},
"awayTeam": {
"isBatting": false,
"id": 46,
"name": "Gloucestershire",
"shortName": "GLO"
},
"currentMatchState": "Live",
"isMultiDay": true,
"matchSummaryText": "Live: Gloucestershire won the toss and elected to bowl.",
"scores": {
"homeScore": "8-293",
"homeOvers": "88.0",
"awayScore": "0-0",
"awayOvers": "0"
},
"liveStreams": [],
"isLive": false,
"currentInningId": 1,
"isMatchDrawn": false,
"isMatchAbandoned": false,
"startDateTime": "2021-04-15T10:00:00Z",
"endDateTime": "2021-04-18T17:00:00Z",
"isWomensMatch": false,
"isGamedayEnabled": false,
"removeMatch": false
},
{
"id": 49942,
"matchTypeId": 15,
"series": {
"id": 2739,
"name": "LV= Insurance County Championship 2021",
"shortName": "LV= Insurance County Championship 2021"
},
"name": "",
"status": "LIVE",
"venue": {
"name": "The Spitfire Ground, St Lawrence",
"shortName": "The Spitfire Ground, St Lawrence"
},
"homeTeam": {
"isBatting": false,
"id": 45,
"name": "Kent",
"shortName": "KEN"
},
"awayTeam": {
"isBatting": true,
"id": 40,
"name": "Yorkshire",
"shortName": "YRK"
},
"currentMatchState": "Live",
"isMultiDay": true,
"matchSummaryText": "Live: Yorkshire won the toss and elected to bat.",
"scores": {
"homeScore": "0-0",
"homeOvers": "0",
"awayScore": "8-358",
"awayOvers": "100.0"
},
"liveStreams": [],
"isLive": false,
"currentInningId": 1,
"isMatchDrawn": false,
"isMatchAbandoned": false,
"startDateTime": "2021-04-15T10:00:00Z",
"endDateTime": "2021-04-18T17:00:00Z",
"isWomensMatch": false,
"isGamedayEnabled": false,
"removeMatch": false
},
]
I am retrieving the match list from this response as follows:
final list = map['matchList']['matches'] as List;
I have a Model class which represents each match from the matches key:
class MatchModel {
int id;
int matchTypeId;
Series series;
String name;
String status;
Venue venue;
HomeTeam homeTeam;
HomeTeam awayTeam;
String currentMatchState;
bool isMultiDay;
String matchSummaryText;
Scores scores;
List<Null> liveStreams;
bool isLive;
int currentInningId;
bool isMatchDrawn;
bool isMatchAbandoned;
String startDateTime;
String endDateTime;
bool isWomensMatch;
bool isGamedayEnabled;
bool removeMatch;
MatchModel(
{this.id,
this.matchTypeId,
this.series,
this.name,
this.status,
this.venue,
this.homeTeam,
this.awayTeam,
this.currentMatchState,
this.isMultiDay,
this.matchSummaryText,
this.scores,
this.liveStreams,
this.isLive,
this.currentInningId,
this.isMatchDrawn,
this.isMatchAbandoned,
this.startDateTime,
this.endDateTime,
this.isWomensMatch,
this.isGamedayEnabled,
this.removeMatch});
MatchModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
matchTypeId = json['matchTypeId'];
series =
json['series'] != null ? new Series.fromJson(json['series']) : null;
name = json['name'];
status = json['status'];
venue = json['venue'] != null ? new Venue.fromJson(json['venue']) : null;
homeTeam = json['homeTeam'] != null
? new HomeTeam.fromJson(json['homeTeam'])
: null;
awayTeam = json['awayTeam'] != null
? new HomeTeam.fromJson(json['awayTeam'])
: null;
currentMatchState = json['currentMatchState'];
isMultiDay = json['isMultiDay'];
matchSummaryText = json['matchSummaryText'];
scores =
json['scores'] != null ? new Scores.fromJson(json['scores']) : null;
if (json['liveStreams'] != null) {
liveStreams = new List<Null>();
json['liveStreams'].forEach((v) {
});
}
isLive = json['isLive'];
currentInningId = json['currentInningId'];
isMatchDrawn = json['isMatchDrawn'];
isMatchAbandoned = json['isMatchAbandoned'];
startDateTime = json['startDateTime'];
endDateTime = json['endDateTime'];
isWomensMatch = json['isWomensMatch'];
isGamedayEnabled = json['isGamedayEnabled'];
removeMatch = json['removeMatch'];
}
How do i map data from the list of matches to the list of my MatchModel? Do let me know if you need anything else, any help will be appreciated.
the thing is the response object which is returned is actually a string, so you need to first convert that to json using like
var json = jsonDecode(response).
Once you have it in json format what you can do is access the list as json['matchList']['matches']. So now you can iterater over it like
List<MatchModel> matches = []
for(var match in json['matchList']['matches']){
matches.add(MatchModel.fromJson(match));
}
Hope it's useful.
I would recommend JSON serialization with code generation. In that way you just need a annotation #JsonSerializable for the class, a constructor and part 'match.g.dart'; at the begin of your file. After this, the json_serializable package will generate the Json-converter-methods/factories for you.
For more information you can use this article: https://flutter.dev/docs/development/data-and-backend/json.
Try this.
var json = jsonDecode(response.body)['matchList']['matches'];
List<MatchModel> matches = List.from(json).map((e) => MatchModel.fromJson(Map.from(e))).toList();

How to match id with current id in array

How I will check current user id == id and show user like or not in UI
"reference":[
{
"id":"123",
"userid"234"
},
{
"id":"1423",
"userid"25534"
},
{
"id":"15423",
"userid"2335534"
},
]
if this is json response try to convert it in models using https://javiercbk.github.io/json_to_dart/
or here is code that can work for u
var reference = [
{"id": "123", "userid": "234"},
{"id": "1423", "userid": "25534"},
{"id": "15423", "userid": "2335534"},
];
var r = reference.firstWhere((e) => e["id"] == "123");
print(r);
// output
{id: 123, userid: 234}

How can I paginate using Resource<T> using Page<T>

I am using the following code to create a paginated list of JSON data for Artist objects:
#RequestMapping(value = "/artists/all", method = RequestMethod.GET, produces = {"application/hal+json"})
public Resources<Artist> getArtists(Pageable pageable) {
final Page<Artist> allArtists= artistService.GetAllArtists(pageable);
for (final Artist artist : allArtists) {
Long artistId = artist.getArtistId();
Link selfLink = linkTo(methodOn(ArtistController.class).getAllArtistById(artistId)).withSelfRel();
artist.add(selfLink);
final Link ordersLink = linkTo(methodOn(MusicController.class).getMusicByArtistId(artistId, pageable)).withRel("musics");
artist.add(ordersLink);
}
Link link =linkTo(ArtistController.class).withSelfRel();
Resources<Artist> result = new Resources<>(allArtists,link);
return result;
}
The code currently returns outputs that are in this format:
{
"artistId": 2,
"name": "Simon Mburu",
"_links": {
"self": {
"href": "http://localhost:8000/api/v1/artists/2"
},
"musics": {
"href": "http://localhost:8000/api/v1/musics/artist/2"
}
}
}
However my intent is to have the code return an output like this:
"pageable": {
"sort": {
"sorted": false,
"unsorted": true
},
"offset": 0,
"pageSize": 20,
"pageNumber": 0,
"paged": true,
"unpaged": false
},
"last": true,
"totalPages": 1,
"totalElements": 2,
"size": 20
"number": 0,
"numberOfElements": 2
"sort": {
// ETC...
What changes can I make to my code to get it to output the data contained in the above example instead of what it currently outputs?