I want to convert from
MultiMap<String, String> byState = ArrayListMultimap.create();
multiMap.put("california", "San Jose");
multiMap.put("california", "San Diego");
multiMap.put("california", "San Francisco");
multiMap.put("Texas", "Austin");
to
Map<String, Integer> numberOfCitiesByState = Maps.immutableEntry("california",3).immutableEntry("Texas", 1).build()
Is there any guava api to do this in an elegant manner ?
Thanks,
Ravi
If you don't actually need a Map<String, Integer>, you could just call byState.keys() and get a Multiset<String> which should have the behavior you're looking for.
simply calling:
byState.get(stateName).size();
seems simple enough.
Related
long story short that I need to get a List< title > of all todos, but now I just have a List< Todo >, so how can I return this List?
get a Stream<List>
static Stream<List<Todo>> readTodos() => FirebaseFirestore.instance
.collection('todo')
.orderBy(TodoField.createdTime, descending: true)
.snapshots()
.transform(Utils.transformer(Todo.fromJson));
and then with StreamBuilder I am able to get a List, but for a method I just need all name of these todos, so I hope in the end it will look like this:
todoTitle: [
'eat',
'drink',
'run',
]
so what I can do? Thanks a lot!
Update
I dont know if the following is a solution, but it does not work yet:
final provider = Provider.of<TodosProvider>(context);
final todos = provider.todos;
List<String> userTitle = todos.map['Todo'].where((todo) => todo['title'] != null).map((value) => value['title']).toList();
and then i got an error from map['Todo'], the error is (The operator '[]' isn't defined for the type 'Iterable<T> Function<T>(T Function(Todo))'.), please help T T thanks!
There are two solution(thanks Frank's reply from another stack):
a. create another collection which just contains title, and then get List< Title > easily.
b. fetch all data as current solution, and I use forEach to seperate the value to a List(I still don't know how to do it in map(), plz help me if anyone has any idea):
create List< String > to get all titles
List< String > titles = [];
get List< Todos > as above displayed in the way of StreamBuilder, and then get all List with provider
final provider = Provider.of<TodosProvider>(context);
final todos = provider.todos;
User forEach to put just todo.title in List< String > titles
getAllTitles(todos){
todos.forEach((todo) {
titles.add(todo.title);
});
}
I believe there is a smart way like h8moss showed me, to create another Stream<List> todoTitles, but then I need to listen another stream, I am new to firestore and flutter world, i dont know which one is better or how to do Stream<List> in the right way.. I just put my solution here in case I forget in the future.
If what you want is to get some part of the Todo class (in this case the title) You can use the Stream.map method:
static Stream<List<String>> readTodoTitles() => FirebaseFirestore.instance
.collection('todo')
.orderBy(TodoField.createdTime, descending: true)
.snapshots()
.transform(Utils.transformer(Todo.fromJson))
.map<String>((list) =>
list.map((element) => element.title,
).toList());
I am trying to get address and city name of a LatLng point using google_geocoding:
var googleGeocoding =
GoogleGeocoding("MY_KEY");
var result = await googleGeocoding.geocoding.getReverse(LatLon(lat, lng));
print(result?.results?.first.formattedAddress.toString());
The result of the print:
Corso Italia, 22-24, 20122 Milano MI, Italy
I need to get only Corso Italia, the string before the comma and Milano, how can I get that?
I tried to use addressComponents, but I only got numbers (especially if I select locations in countries like Italy)
print(result?.results?.first.addressComponents?.first.longName.toString());
It may not be the most optimal but you could play with picking the string through the spaces and then make the string in such a way that you can have the sequence you want
I currently have data like this:
_classes = _items.map((e) => e.ClassID).toSet();
print(_classes);
{One, Two} // output
and I am trying to achieve data look like this:
{'One', 'Two'}
But I can't solve it. Any suggestions why is that?
I already got it after hours of trying and trying different codes.
Set<String> _classes;
_classes = _items.map((e) => e.ClassID.toString()).toSet();
The .toString() part is the one that I am looking for.
I developed a app using flutter 1.0. The app works well on most android and ios phones. But I found there one android phone and one iphone can not open that app, just show the error message "type '_Smi' is not a subtype of type 'double'". Is there someone can tell me what's going on my app.
Error picture when open the flutter app:
It's hard to tell without the relevant piece of code, but in my case, this happened when trying to assign a double value from a Map. The solution was simply to call .toDouble on the value:
// myMap is a Map<String, dynamic>
double myDouble = myMap['mykey'].toDouble();
It used to work without the .toDouble(), but the _Smi error started happening one day.
_Smi stands for Small machine integers, according to Dart Cookbook
So basically you're getting an int and parsing it incorrectly.
I had the same problem and settled on this.
Try to replace this:
double myDouble = myMap['mykey'].toDouble();
To this:
double myDouble = double.parse(myMap['mykey'].toString());
this helped me to read json from another api.
double temp = weatherData['main']['temp'].toDouble();
when you are using firestore (from google firebase) and you are having fields in a document that are stored as number (only number available, so number is used for int, double, float, ...) - make sure that you use .toDouble() before assigning the field value of a document to a double field in your model class in dart.
Example:
final collectionReference =
FirebaseFirestore.instance.collection("Products");
final products = await collectionReference.get();
List productsDocuments = products.docs
.map((doc) => doc.data())
.toList();
items = Items.fromList(productsDocuments);
List<Item> items;
factory Items.fromList(docsFirebase) => Items(
items: List<Item>.from(docsFirebase.map((docFirebase) => Item(
itemName: docFirebase['item_name'],
variantId: docFirebase['variant_id'],
imageUrl: docFirebase['image_url'],
barcode: docFirebase['barcode'],
defaultPrice: docFirebase['default_price'].toDouble(),
lowStock: docFirebase['low_stock'],
optimalStock: docFirebase['optimal_stock']))));
}
I need to update a DataSourceTextField. Basically I do this in my code:
DataSourceTextField partDataSourceField = new DataSourceTextField(
partFieldName, constants.partTitle());
partDataSourceField.setValueMap(partCodesList);
documentsResultDataSource.setFields(partDataSourceField,
titleDataSourceField);
That code, generates a "part" list on the DataSource for me to filter the results.
What I've been trying is this dynamically change this list to set it to show only the values that are available on the results. I've tried this with no avail:
DataSourceField partField = documentsResultDataSource.getField(partFieldName);
LinkedHashMap<String, String> partCurrentCodesList = new LinkedHashMap<String, String>();
partCurrentCodesList.put("Test", "Test");
partField.setValueMap(partCurrentCodesList);
Is it possible to accomplish what I need?
I deleted the DataSourceTextField and then :
documentsResultDataSource.setFields(partDataSourceField,
titleDataSourceField);
This is sub-optimal but the best solution I found.