how to create array in flutter apis - flutter

I want submit Selected answers array how can do this.
How to pass selected answer in this array

Flutter/Dart doesn't have arrays. Use lists instead.

Solution
In the api-response ,it's always formatted into either List of Map or Map of List.
List of Map is Like :
[
{
"name":"ruby",
"gender":"female"
},
{
"name":"otis",
"gender":"male"
},
]
And, Map of List is Like :
{
"data": [
"Professor",
"Berlin",
"Tokyo"
]
}
So to access them you have to use JsonDecode and then look the response and process that.
For Map response ....
var resMap = jsonDecode(response.body);
For List response (use key after resMap with key)...
var resMap = jsonDecode(response.body);
var infoList = resMap["data"];
Demo
class CatTypeController {
Future<void> getLeaves() async {
String url = "https://meowfacts.herokuapp.com/?count=2";
http.Response response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
Map rM = jsonDecode(response.body);
print(rM["data"]);
}
}
}
Response
Output
["In ancient Egypt, killing a cat was a crime punishable by death.","The way you treat kittens in the early stages of it's life will render it's personality traits later in life."]

Related

How to post a data using dio to an array wrapped inside a json and inside that array is also a json

How to post a data using dio to an array wrapped inside a json and inside that array is also a json. the structure of response is like below :
{
"result":[
{
"title":"String",
"caption":"String"
"related":[
{
"relatedTitle":"String",
"relatedCaption":"String"
}
]
}
]
}
I want to post value to the relatedTitle and relatedCaption inside the related key.
Please help out in it.
try to encode your json like:
var body = {
"title":"String",
"caption":"String",
"related":[
{
"relatedTitle":"String",
"relatedCaption":"String"
}
]
};
var response = await dio.post(Url, data: jsonEncode(body),);

Access field names from firebase realtime db through flutter

I am trying to retrieve data from firebase realtime database in my flutter app. My data looks something like this :
This is my code :
var uid = user?.uid;
final ref = FirebaseDatabase.instance.ref('uids/$uid/sessions');
ref.onValue.listen((event) {
for (final child in event.snapshot.children) {
var dataObject = child.value.toString();
print(dataObject);
}
}, onError: (error) {});
It gives me this output :
I/flutter (16144): {2:9: Example728, 3:15: Example644, 1:45: Example, 2:11: Example184, 2:7: Example}
I/flutter (16144): {2:16: Example440, 2:26: Example124, 2:22: Example515}
I want to extract information from this jsonObject. But I have 0 idea how to do it. Do I have to make a model? If yes then how? Because the fields are actually time stamps. And I would want to access them as well as I have to display it on the screen with the date (5-11-2022 and 6-11-2022) as well.
Use this code inside the listen
//dataObject = child.value
Map dataObject = {
"5-11-2022": {
"2:9": "Example728",
"3:15": "Example644",
"1:45": "Example",
"2:11": "Example184",
"2:7": "Example",
},
"6-11-2022": {
"2:16": "Example440",
"2:26": "Example124",
"2:22": "Example515",
},
};
for (MapEntry item in dataObject.entries) {
String day = item.key.toString();
debugPrint("day: $day");
for (MapEntry item2 in dataObject[item.key].entries) {
String hour = item2.key.toString();
String value = item2.value.toString();
debugPrint("hour: $hour value: $value");
}
}

Flutter how to find how many values map has

I have an API, every time when I call it. It returns with a different number of keys.
Sometimes:
{
"json":[
"example",
"example1"
]
}
Other times:
{
"json":[
"example",
"example1",
"example2"
]
}
How can I count how many are there in a map?
once you get your response. you can use
final map = jsonDecode(data) as Map<dynamic, dynamic>?;
print(map?.length); // items on root 1
final response = jsonDecode(data)["json"] as List?;
print(response?.length);

Add element into an existing Map in Cloud Firestore

Through Flutter I want to add a Map element in Firestore.
Instead of fetching the whole map and replacing it with the added element is it possible to directly add a new key and value?
Example:
Map = { '2020-05-21' : true } -- Add --> Map = { '2020-05-21' : true, '2020-05-22': true }
This is how I tried to do this but without any success.
return collection.document('id').updateData({'map.$date' : true});
Use this approach:
final ref = Firestore.instance.document('collection_id/document_id');
await ref.updateData({
'field.key2': 'value2',
});
Since I am not having an idea about how your data looks like on server, I tested this one and it worked.
Edit:
// initial work
var ref = Firestore.instance.document('Employees/54G...Naf');
var initialData = {
'date_1': '1',
};
await ref.setData({
'busy_map': initialData,
});
// updated work
var updatedData = {
'busy_map.date_2': '2',
};
await ref.updateData(updatedData);

Parsing JSON effectively in Flutter/Dart

How to extract a pair of values out of a JSON using dart
This is the function I have so far:
This is the JSON:
{
"displayNames": [
"John Doe",
"ChloƩ Kamgang",
"Lady Testing of Tarth"
],
"users": [
{
"uid": "1tcPRqNZ7wexX2DWa11V9Ay1zES2",
"displayName": "John Doe"
},
{
"uid": "aZg7Emp8H9W42irnM73NBdTe6YM2",
"displayName": "ChloƩ Kamgang",
"photoURL": "https://firebasestorage.googleapis.com/v0/b/atalaku-fcf9e.appspot.com/o/Profilescaled_1e189635-0bc0-4791-ba20-6aded7ad3e8f7210544.jpg621jpg?alt=media&token=f5cffac3-a20c-4a83-8241-4fab16a9bd66"
},
{
"uid": "hXzyTuDE8eafnSxITmz7ZdMQDnw1",
"displayName": "Lady Testing of Tarth",
"photoURL": "https://firebasestorage.googleapis.com/v0/b/atalaku-fcf9e.appspot.com/o/Profilescaled_image_picker8162975920.jpg645jpg?alt=media&token=269007d1-09ee-4fe4-b7ad-72aa7cea756a"
}
]
}
And this is the function:
Future<List<Map<String, dynamic>>> getProfilesBySuggestion(
String sSuggestion) async {
try {
List<Map<String, dynamic>> listToReturn = [];
if (sSuggestion == null ||
sSuggestion.isEmpty ||
!sSuggestion.startsWith('#')) return listToReturn;
//Getting all the names
Map<String, dynamic> listUsers = await getAllUsers();
if (listUsers == null) return listToReturn;
//Returning only the names corresponding
List<dynamic> listNames = listUsers['displayNames'];
for (String name in listNames)
if (name
.toLowerCase()
.startsWith(sSuggestion.substring(1).toLowerCase())) {
List<Map<String, dynamic>> listOfusers = listUsers['users'] as List<Map<String, dynamic>>;
Map<String, dynamic> rightOne = listOfusers.firstWhere((user) => user['displayName'] == name);
String sPhotoURL = rightOne['photoURL'];
print('** name = $name, photoURL = $sPhotoURL');
listToReturn.add({'name': name, 'photoURL': sPhotoURL});
}
return listToReturn;
} catch (error) {
print('*** Error During getProfilesBySuggestion: ${error.toString()}');
return [
{'errorMessage': error.toString()}
];
}
}
What I want is a list of pair (name, photoURL). I am using the flutter_typeahead plugin, I want to display a list of names and their respective avatars. As you can see, I am using Firebase. Please let me know if there is a better option as well, as this will get pretty heavy with scale. Thank you!
A good starting point when working with data that's not organised the way you want it, is to re-organize it. I'd merge the two lists adding the display name to each user. But, of course, you see immediately that that's not necessary as each user already contains their display name. (The displayNames branch of your json is unnecessary for your purposes.)
So, you can just work with the users branch. Note that what you are doing is extracting the members of the users list and subtly changing the tag name (from displayName to name - leaving photoURL the same). Is the tag name change necessary? If not you could basically achieve what you want with a single where.
That said, this should achieve what you want (including the tag name change):
Future<List<Map<String, dynamic>>> getProfilesBySuggestion(
String sSuggestion) async {
try {
if (sSuggestion == null ||
sSuggestion.isEmpty ||
!sSuggestion.startsWith('#')) return [];
//Getting all the names
Map<String, dynamic> allUsers = await getAllUsers();
if (allUsers == null) return [];
//Returning only the names corresponding
List<dynamic> users = allUsers['users'];
var suffix = sSuggestion.substring(1).toLowerCase();
return users
.where((user) => user['displayName'].toLowerCase().startsWith(suffix))
.map<Map<String, dynamic>>((user) => {
'name': user['displayName'],
'photoURL': user['photoURL'],
})
.toList();
} catch (error) {
print('*** Error During getProfilesBySuggestion: ${error.toString()}');
return [
{'errorMessage': error.toString()}
];
}
}
A good starting point when working with data that's not organised the way you want it, is to re-organize it.
And if that's not an option, you can still mitigate the impact. It's always easier to work with plain old dart classes than json, so I'd encourage you to map the json to classes.
I usually use package:built_value for that. There is a tool that helps map json:
https://charafau.github.io/json2builtvalue/ Careful, it's not 100%. Eg. it will not include photoUrl field if you just copy-paste your json.
Basically, I'd take the json.users, and map it to objects. Make sure to make photoUrl optional.
Once that's done, you can create any lookup table you want. You could just have a List<User> to iterate over names and photoUrls, or you could create a Map<String, User> to look up users by their name.
Tip: class Map has got a number of constructors that you can work with.