Flutter dropdown can't have duplicate values? But unfortunately I have those as it is fetching from an API - flutter

My dropdown is having duplicate values as it is fetching Pincode data from an API. Can someone help me to fix this error as the dropdown cant have duplicate values? How to stop duplicate values while fetching the data from the API?enter image description here

You can convert your list to set and then again back to list for to delete duplicated values. Set doesnt contain duplicated values. For more check out documentation of set

void main() {
final myList = [
{
'a': 'apple',
'name':'sam',
'age': 41,
},
{
'a': 'apple',
'name':'alex',
'age': 43,
},
{
'a': 'ban',
'name':'robby',
'age': 41,
}
];
var uniqueIds = myList.map((o) => o["a"]).toSet().toList();
print(uniqueIds);
}
Mapping the list with specific key and then => conversion of toSet() and toList() solves my problem

Related

Flutter FireStore Create, Read and Update Array with a Map Object

Fairly new to Flutter and FireStore, I'm having trouble finding examples or explanations on how to add Maps to an Array (specifically, Creating the initial Array with a Map, then Reading then Adding more Maps to the collection of the Notes Array).
I have an Event Class for scheduling events and that is working very well. What I'm trying to add is a "Notes" field that would allow an some Administrator to add Notes on one day then come back and add to that Event another set of notes as things change. I don't want to "overwrite" the previous Notes, just keep adding more Notes to the Array of notes.
Specific questions:
How do I Create the "Array" when adding the entry into FireStore using Flutter?
How do I Read the data in the "Array" when it's coming back as a set of "Map fields" in Flutter?
How do I just Add to the Array with a new Note? (I think this needs FieldValue.arrayUnion([someMap]) but I'm not certain as this appears to avoid any overwriting.
The page section here shows writing it out but little else: https://firebase.google.com/docs/firestore/manage-data/add-data#data_types
Below is an example of the FireStore structure I'm trying to create.
Has anyone done this before and do you have some direction you can provide? The Firebase documentation in this space is thin...
To create an new document with array in firestore:
FirebaseFirestore.instance.collection('path/to/collection').add(
{ 'notesArray': [
{'date': 'sometime', 'notes': 'somenotes', 'user': 'someuser'}
]},
SetOptions(merge: true),
);
// or
FirebaseFirestore.instance.collection('path/to/collection').add(
{ 'notesArray': []}, // for an empty array
SetOptions(merge: true),
);
To read the data:
FirebaseFirestore.instance.doc('company').get().then((value) {
final doc = value.data()!;
print(doc['lname']); // should print Gethsemane
print(doc['notesArray'] as List); // should print notes array
final notes = doc['notesArray'] as List;
for (final note in notes) {
print(note['date']);
print(note['notes']);
print(note['user']);
}
// or
for (int i = 0; i < notes.length; i++) {
print(notes[i]['date']);
}
});
Add new data to notes array. Simply use FieldValue.arrayUnion.
E.g
FirebaseFirestore.instance.doc('path/to/doc').set(
{
'notesArray': FieldValue.arrayUnion([
{'date': 'sometime', 'notes': 'somenotes', 'user': 'someuser'}
]),
},
SetOptions(merge: true),
);
// I used set method along with setOptions in order not to
// override other fields (e.g modifiedBy field)
Keep in mind that if your array is going to be very large, it is better to store the notes as a subcollection.
##EDIT##
If you want to update a nested array, you can use the dot notation.
class SchedulerEvents {
final List<Map<String, dynamic>>? notes;
SchedulerEvents({required this.notes});
}
// lets assume we have data like this that we want to update
final data = SchedulerEvents(
notes: [
{'date': 'sometime', 'notes': 'somenotes', 'user': 'someuser'},
],
);
FirebaseFirestore.instance.doc('path/to/doc').set(
{
'schedulerEvents.notes': FieldValue.arrayUnion([data.notes![0]]),
// or
'schedulerEvents.notes': FieldValue.arrayUnion(data.notes![0]),
// 'schedulerEvents.lname: 'test', // to update other fields
},
SetOptions(merge: true),
);
// we used dot notation to update fields here.

Filter and manipulate a map

It's the first time I use Dart and I'm stuck with a simple thing.
I have a simple Map and I need to remove some items from this map and modify the content.
I have this:
Map<String, List<String>> dataset = {
'apple': ['apple1', 'apple2', 'apple3'],
'pear': ['pear1', 'pear2'],
'ananas': ['ananas1', 'ananas2', 'ananas3'],
'orange': ['orange1', 'orange2', 'orange3', 'orange4'],
};
List<Map<dynamic, String>> fruits = [
{'key': 'pear', 'labelToShow': 'Pear fruit'},
{'key': 'ananas', 'labelToShow': 'My ananas'},
];
and I would like to have this:
Map<String, Map<String, List<String>>> result = {
'pear': {
'values': ['pear1', 'pear2'],
'labelToShow': 'Pear fruit'
},
'ananas': {
'values': ['ananas1', 'ananas2', 'ananas3'],
'labelToShow': 'My ananas'
},
};
So, basically, I need to remove from dataset the items that have the key that it's not included in fruits (in field key) and then I need to add the field labelToShow.
I dont' know ho to do that.
I started removing items from dataset doing so:
dataset.removeWhere((k, v) => k != 'pear' && k != 'ananas');
but I don't like, I would like to loop through fruits.
Can someone please help me?
Thanks a lot
I wouldn't remove anything from dataset. Instead I'd build a new map from scratch, with just the data you want.
How about:
Map<String, Map<String, List<String>>> result = {
for (var fruit in fruits)
fruit["key"]: {
"values": dataset[fruit["key"]],
"labelToShow": fruit["labelToShow"]
}
};

Hello there, how to check which lists in a class have expired time element in them?

In a class I have lists, in those lists I have maps, each map has 'interval' and 'time' element, I want to check which of those 'time' elements have expired and then pass those lists to further sorting according to interval (this sorting thing is working already), just not sure how to check which lists have expired 'time' in them?
In the code I have marked with //TODO part that is missing
Thank you
class QuizBrain {
List<Map<String, dynamic>> products = [
{
'id': 24,
'interval': 10000,
'time': '2021-12-14 20:37:21.190473',
},
{
'id': 36,
'interval': 20000,
'time': '2020-11-14 20:37:21.190453',
},
{
'id': 48,
'interval': 30000,
'time': '2020-12-14 20:37:21.190453',
},
];
min() {
//TODO need to set condition to check which lists 'time' is expired, then i pass those that 'time is expired to further sorting beneath
if (products != null && products.isNotEmpty) {
products.sort((a, b) => a['interval'].compareTo(b['interval']));
//print(products);
return (products.first['id']);
}
}
}
You should be able to convert the time attributes into DateTime objects and compare them to now using compareTo:
final now = DateTime.now();
final expired = products.where((item) {
final itemTime = DateTime.parse(item["time"]);
return itemTime.compareTo(now) < 0;
});
Then if I've read your question correctly you just need to replace products with expired in your if statement.
This is from the docs of compareTo():
this.compareTo(other)
Compares this DateTime object to [other], returning zero if the values are equal.
Returns a negative value if this DateTime [isBefore] [other].
It returns 0 if it [isAtSameMomentAs] [other], and returns a positive value otherwise (when this [isAfter] [other]).

How to check key value id exits or not in array of object in Flutter?

How to check value is exits or not in an array of objects. Please give me a solution if it works then I accept your answer Anyone here with a solution for this? Thanks in Advance. Here is my code.
[{"index":0,"productId":"5d9890c7773be00ab5b41701","qty":2}, {"index":0,"productId":"5d9890c7773be00ab5b41701","qty":3}]
how to check ProductId is exited or not of this array in Flutter.
Your List have duplicate value. In my demo, add an extra index 1 to prove it work
For unique and index only , use indexWhere
For return qualified list use where , firstWhere, singleWhere
You can see DarPad result
code snippet
void main() {
List<Map> productList = [{"index":0,"productId":"5d9890c7773be00ab5b41701","qty":2}, {"index":0,"productId":"5d9890c7773be00ab5b41701","qty":3}, {"index":1,"productId":"5d9890c7773be00ab5b41702","qty":23}];
int index = productList.indexWhere((prod) => prod["productId"]=='5d9890c7773be00ab5b41701' );
print(index);
var prodLists = productList.where((prod) => prod["productId"] == '5d9890c7773be00ab5b41701');
print('${prodLists}');
}
Output
0
({index: 0, productId: 5d9890c7773be00ab5b41701, qty: 2}, {index: 0, productId: 5d9890c7773be00ab5b41701, qty: 3})

How to search a list of Object by another list of items in dart

How to search a list of a class object with one of its property matching to any value in another list of strings
I am able to get filtering based on a single string , but not on a list of strings
final List<shop_cart.ShoppingCart> cartprd = snapshot.documents
.map((f) => shop_cart.ShoppingCart.fromMap(f.data))
.toList();
List<SomeClass> list = list to search;
List<String> matchingList = list of strings that you want to match against;
list.where((item) => matchingList.contains(item.relevantProperty));
If the number of items in list is large, you might want to do:
List<SomeClass> list = list to search;
List<String> matchingList = list of strings that you want to match against;
final matchingSet = HashSet.from(matchingList);
list.where((item) => matchingSet.contains(item.relevantProperty));
Or else just always store the matching values as a hashset.
In case if you want to check for a value in a list of objects . you can follow this :
List rows = [
{"ags": "01224", "name": "Test-1"},
{"ags": "01224", "name": "Test-1"},
{"ags": "22222", "name": "Test-2"},
];
bool isDataExist(String value) {
var data= rows.where((row) => (row["name"].contains(value)));
if(data.length >=1)
{
return true;
}
else
{
return false;
}
}
you can put your own array of objects on rows . replace your key with name . you can do your work based on true or false which is returned from the function isDataExist
As of today, you can't.
(A side note : You can use .where, .singleWhere, .firstWhere. This site explains various list/array methods.)
You can simply use List.where() to filter a list
final List<shop_cart.ShoppingCart> cartprd = snapshot.documents
.where((f) => shop_cart.ShoppingCart.contains(f.data));
var one = [
{'id': 1, 'name': 'jay'},
{'id': 2, 'name': 'jay11'},
{'id': 13, 'name': 'jay222'}
];
int newValue = 13;
print(one
.where((oldValue) => newValue.toString() == (oldValue['id'].toString())));
OUTPUT : ({id: 13, name: jay222})
store output in any variable check if variable.isEmpty then new value is unique either
var checkValue = one
.where((oldValue) => newValue.toString() == (oldValue['id'].toString()))
.isEmpty;
if (checkValue) {
print('Unique');
} else {
print('Not Unique');
}
OUTPUT : Not Unique