I want to reverse the key and value of Map - flutter

How can I reverse the key and value of the map?
for example, {1:a , 2:b , 3:c} => {a:1 ,b:2 ,c:3}

Try this piece of code:
Map<int, String> map = {1: "a", 2: "b", 3: "c"};
Iterable<String> values = map.values;
Iterable<int> keys = map.keys;
Map<String, int> reversedMap = Map.fromIterables(values, keys);
print(reversedMap); // {a:1 ,b:2 ,c:3}

You can do this:
const items = {1:'a' , 2:'b' , 3:'c'};
void main() {
final inverted = items.map((key, value) => MapEntry(value, key));
print(inverted);
}
It logs
{a: 1, b: 2, c: 3}

Related

how to sum list values from API in flutter

Does anyone here know/have references/examples of how to add up the values in the list in Flutter. Thanks
use sum:
import 'package:collection/collection.dart';
void main() {
final list = [1, 2, 3, 4];
final sum = list.sum;
print(sum); // prints 10
}
Your question is similar to the question here, refer to it for more information
you can use .fold() method
fold method:
T fold<T>(T initialValue, T Function(T, Data) combine)
example for sum list of object:
void main() {
List<Data> listData = [
Data(count: 10, name: 'a'),
Data(count: 12, name: 'bc'),
Data(count: 21, name: 'abc'),
];
int sum = listData.fold(0, (int preValue, data) => preValue + data.count);
print(sum);// 43
}
class Data {
int count;
String name;
Data({required this.count, required this.name});
}

Append value of type List to a map

I have a class of type Produit
class Produit {
String? nom;
double? prix;
int? quantite;
Produit({this.nom, this.prix, this.quantite});
}
I have a List of type Produit
List<Produit> listeProduits = [
.
.
.
]
and i have this map
Map<int, List<Produit>> listePanier = {};
I'm trying to append a new value of type Produit to this map each time a button is pressed .
You can do something like this using the update method on Map to make so we handle situations where the key are already in the list (where we then want to append to the existing list) and where the key is missing (where we then want to create a new list with out element):
void main() {
final Map<int, List<String>> myMap = {
1: ['String1', 'String2']
};
print(myMap);
// {1: [String1, String2]}
String newValueToList = 'NewString3';
// Example of what happens in case the key already exist
myMap.update(1, (list) => list..add(newValueToList),
ifAbsent: () => [newValueToList]);
print(myMap);
// {1: [String1, String2, NewString3]}
newValueToList = 'NewString4';
// Example of what happens if the key does not already exist. In this case
// we create a new list with the new item
myMap.update(2, (list) => list..add(newValueToList),
ifAbsent: () => [newValueToList]);
print(myMap);
// {1: [String1, String2, NewString3], 2: [NewString4]}
}
We can also create an extension to help us doing this:
void main() {
final Map<int, List<String>> myMap = {
1: ['String1', 'String2']
};
print(myMap);
// {1: [String1, String2]}
myMap.appendToList(1, 'NewString3');
print(myMap);
// {1: [String1, String2, NewString3]}
myMap.appendToList(2, 'NewString4');
print(myMap);
// {1: [String1, String2, NewString3], 2: [NewString4]}
}
extension AppendToListOnMapWithListsExtension<K, V> on Map<K, List<V>> {
void appendToList(K key, V value) =>
update(key, (list) => list..add(value), ifAbsent: () => [value]);
}

Reorder Array of objects Flutter

Array of object
Input:
[
{id:1,order:1},
{id:2,order:null},
{id:3,order:0},
{id:4,order:null},
{id:5,order:3}
]
Output:
[
{id:3,order:0},
{id:1,order:1},
{id:2,order:null},
{id:5,order:3},
{id:4,order:null}
]
Considering model
Item(int id,int? Order)
By default the order is null and these positions are to be maintained and object having orders are to be moved up or down.
Try this, if the array is of type Map -
arrayOfObjects.sort((a, b) => a['order'].compareTo(b['order']));
Or this if it is holding Item class with an order attribute
arrayOfObjects.sort((Item a, Item b) => a.order.compareTo(b.order));
Note - You can remove items with null order before running the sort.
Example
arrayOfObjects.removeWhere((item)=> item.order == null);
The double Iterations are based on the length of the array to handle the nulls.
Solution
import 'package:collection/collection.dart';
class Item {
int? _id;
int? _order;
Item({int? id, int? order}) {
this._id = id;
this._order = order;
}
int? get id => _id;
set id(int? id) => _id = id;
int? get order => _order;
set order(int? order) => _order = order;
Item.fromJson(Map<String, dynamic> json) {
_id = json['id'];
_order = json['order'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this._id;
data['order'] = this._order;
return data;
}
}
List<Item> reorder(List<Item> it){
var tempData = it;
tempData.forEach((_){
tempData.forEachIndexed((index,val){
///Remove original and replace
var ind = val.order;
if(ind!=null){
///Check if it is at the Proper Position
if (index == ind) {
return;
}
var first = it.removeAt(index);
it.insert(ind as int, first);
}
});
});
return it;
}
void main() {
var list = [
Item(id: 1, order: 1),
Item(id: 3, order: 2),
Item(id: 2, order: 7),
Item(id: 4, order: null),
Item(id: 5, order: null),
Item(id: 6, order: null),
Item(id: 7, order: 6),
Item(id: 8, order: 4)
];
list.forEach((it) => print('${it.id} ->${it.order}'));
var first = reorder(list);
print('\n');
first.forEach((it) => print('${it.id} ->${it.order}'));
///Stack List
}

How can I use firstWhereOrNull with a map in Flutter?

How can I use firstWhereOrNull with maps in Flutter?
In other words, how can I do this:
final myVariable1 = myList.firstWhereOrNull(
(myVariable2) =>
!myList.containsValue(myVariable2));
Instead of using a list (myList), I'd like to do the same with a map (Map<String,int>).
Map<String,int> myMap = {};
myMap("stuff1") = 1;
myMap("stuff2") = 2;
myMap("stuff3") = 3;
Thanks
There is no such firstWhereOrNull method for Maps, but you can easily come up with one using extension methods:
extension ExtendedMap on Map {
/// The first entry satisfying test, or null if there are none.
MapEntry? firstWhereOrNull(bool Function(MapEntry entry) test) {
for (var entry in this.entries) {
if (test(entry)) return entry;
}
return null;
}
}
Here is how you can use it:
final map = <String, int>{
'stuff1': 1,
'stuff2': 2,
'stuff3': 3,
};
final test = map.firstWhereOrNull((entry) => entry.value == 2);
print(test); // Prints MapEntry(stuff2: 2)
final nullTest = map.firstWhereOrNull((entry) => entry.key == "stuff5");
print(nullTest); // Prints null
So, I created this implementation, I don't think it's the most optimized, also because it was necessary to use the cast since because of the sound null safety, it's not possible to return any value. But it works for you.
var myMap = {"key1": "value", "key2": 3};
var result = myMap.entries
.cast<dynamic>()
.firstWhere((e) => e.key == "key", orElse: () => null);
print(result);
I hope this helps in some way!

Dart Flutter: How to compare int values of a Map?

Say that I have a Map<String, int> containing entries and I would like to select the first entry with the highest value, see the example below:
Map<String, int> wordCount = {
'foo' : 3,
'bar' : 3,
'john' : 4,
'doe' : 3,
'four' : 4
}
What is the most efficient way to get john as it has the first highest value?
You can use something like this:
print(wordCount.entries.reduce((maxEntry, entry) {
return maxEntry.value < entry.value ? entry : maxEntry
}).key);
Something like this?
void main() {
Map<String, int> wordCount = {
'foo': 3,
'bar': 3,
'john': 4,
'doe': 3,
'four': 4
};
final nameWithHighestValue =
wordCount.entries.reduce((a, b) => a.value >= b.value ? a : b).key;
print(nameWithHighestValue); // john
}