Flutter: Gsheets. Is there any way to pull values without keys? - flutter

I'm using this function to pull key, latitude, and longitude:
Map<double, double> m2 = (await sheet.values.map.column(3, fromRow: 2)).map(
(key, value) => MapEntry(
double.parse(key), value == null ? null : double.tryParse(value)));
List longitudelist = m2.values.where((value) => value != null).toList();
Latitude is of course pulled with the same, just with columns 2 from row 2.
Column 1 is numebered. one through how ever many points I have...
Is there any way I can simply pull latitude and longitude values and completely ignore keys? I want to be able to have latitude in column 1, longitude in 2, and nothing more.

Sure try to use ForEach( (e) { return Your_Funcation ; }
Check this for more :
https://api.dart.dev/stable/2.9.1/dart-core/Iterable/forEach.html

Related

This row does not contain values for that table

I'm using Drift(moor).
When trying to get a sample of data using leftOuterJoin, the following situation happens:
The table that I join via leftOuterJoin returns null as a value.
I.e. leftOuterJoin itself works correctly but values from joined table are not read and return null.
As a result, I get a row where 1 or 2 columns have null values (depending on what table I join)
No one with such a situation is not faced?
final rows = await (select(favoritePlaces).join(
[
leftOuterJoin(
cachedPlaces, cachedPlaces.id.equalsExp(favoritePlaces.placeId)),
],
)).get();
parsedExpressions
Remove ".get()" from the last line.
Add below lines after your code:
final result = await rows.get();
return result.map((resultRow) {
return FavoritePlacesWithcachedPlaces(
resultRow.readTable(favoritePlaces),
resultRow.readTableOrNull(cachedPlaces),
);
}).toList();
where FavoritePlacesWithcachedPlaces object is something like:
class FavoritePlacesWithcachedPlaces {
final FavoritePlaces favoritePlaces;
final CachedPlaces? cachedPlaces;
FavoritePlacesWithcachedPlaces (this.favoritePlaces,
this.cachedPlaces);}
The key point is using "readTableOrNull".

Get index of list of map from map

How do you get index of list of maps from a map. I tried to use indexOf which works but by the time the position of values are mixed up then it returns -1.
UPDATE: It actually doesn't work even in right order
List<Map<String, dynamic>> list = [{'id':1, 'name':'a'}, {'id':2, 'name':'b'}];
Map<String, dynamic> item = {'name':'a','id':1}; //<- position name and id are in different places
print(list.indexOf(item)); // so it return -1
The best way would be to get index of list where item contains same id ... if you know what I mean... How to do it?
You can use indexWhere instead indexOf.
Map<String, dynamic> item = {'name':'a','id':1};
print(list.indexWhere((i) => i['id'] == item['id'])); // prints 0
Map<String, dynamic> item = {'name':'b','id':2};
print(list.indexWhere((i) => i['id'] == item['id'])); // prints 1

Flutter: Parsing Firebase Realtime Database snapshot to list

I tried searching other questions but the only similar question to this had answers in JavaScript instead of Dart/Flutter. I'm trying to get a list from my Firebase Realtime Database into my app as a List<BaseModel>
So far from what I've searched in the net, I think the result of the DataSnapshot is a map that I could parse so I tried it out but got this error: List<dynamic>' is not a subtype of type 'Map<dynamic, dynamic>
My Code:
Future<List<BaseModel>> getList(
{DatabaseReference query, Models modelType}) async {
List<BaseModel> list = new List();
DataSnapshot snap = await query.once();
Map<String, dynamic> json = Map.from(snap.value);
json.forEach((key, value) {
list.add(BaseModel(model: modelType, key: key, snapshot: value));
});
return list;
}
The weird thing is, even if I try to parse a non-list model I also get the same error.
My database structure looks like this:
Update:
BaseModel:
abstract class BaseModel {
factory BaseModel({Models model, String key, Map map}) {
switch (model) {
case Models.MyModel:
return MyMod.fromSnapshot(key: key, map: map);
break;
default:
throw ("Not a valid model.");
}
}
}
MyModel:
MyModel.fromSnapshot({String key, Map map}) {
_id = key;
_title = map['title'];
}
My Firebase query is just the database reference with .child("Root")
I found a solution!
My new code:
Future<List<BaseModel>> getList({DatabaseReference query, Models modelType}) async {
List<BaseModel> list = new List();
DataSnapshot snap = await query.once();
List<dynamic> resultList = snap.value;
for(var i = 0; i < resultList.length; i++) {
Map<dynamic, dynamic> map = Map.from(resultList[i]);
list.add(BaseModel(model: modelType, key: i.toString(), snapshot: map));
}
return list;
}
This should work assuming you parse the values from your model's .fromMap(yourMap) constructor method. Something like _title = yourMap['key'];
I had a similar experience where the snapshot.value sometimes returned a List and sometimes returned a Map. I searched for a long time to get an answer with no luck but I came up with a workaround.
I suspected that the problem was being caused by using a record key with a value of zero so I added 100 to each key before I wrote it to the db and then subtracted it when I had read and was processing the records. The problem went away in that I then always got a Map returned.
I have since seen a reason given for this behaviour and it confirmed that the zero key value was the culprit but unfortunately I didn't save the link. I think it was on one of the Firebase blogs.
I think the 0 record returns a List and the ones with positive values return a Map.
Anyway, try the adding 100 trick and see it that helps. if it helps, upvote me....I don't think you need code to add or delete 100. :-)
Found the article, Firebase is deciding if it should render an array or a map based on the snapshot content: https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html?m=1
UPDATE:
My 'starting at 0' theory was a red herring, sorry.
The key to this behaviour (bits in bold) is in the part of the Firebase blog (link above) that states:
However, to help people that are storing arrays in Firebase, when you
call .val() or use the REST api to read data, if the data looks like
an array, Firebase will render it as an array.
In particular, if all of the keys are integers, and more than half of
the keys between 0 and the maximum key in the object have non-empty
values, then Firebase will render it as an array. This latter part is
important to keep in mind.
// we send this ['a', 'b', 'c', 'd', 'e'] // Firebase stores this {0:
'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}
// since the keys are numeric and sequential, // if we query the data,
we get this ['a', 'b', 'c', 'd', 'e']
// however, if we then delete a, b, and d, // they are no longer
mostly sequential, so // we do not get back an array {2: 'c', 4: 'e'}
You can't currently change or prevent this behavior.
I have now tested this by setting up a db node that looks like the below image. I tested what was being returned in snapshot.value by using snapshot.value is List and snapshot.value is Map, both return true or false.
When ONLY nodes 0, 1 and 3 were there, Firebase RTDB was happily returning a List in snapshot.value. When I added nodes 4 and 6, which have inconsistent data, it decided it was time to return a Map. :-)
So, the quick fix is to test the contents of snapshot.value with is List and/or is Map and then process the contents accordingly, otherwise rethink your keys...the fact that they are sequential or close-to-sequential (with gaps) but have the same children structure is the issue.

How to filter the OrderBy

i am retrieving data from database on the base of there id, as can be seen,
public ActionResult loadEpisodes(int id, string name, int epId)
{
ViewBag.LoadEps = db.VideoEpisode
.Where(ve => ve.VideoId == id && ve.IsActive == true)
.OrderByDescending(c => c.Sequence);
//some other code removed for the ease
return view();
}
It will return the episodes of some 'id' and in descending sequence value.
My question is, if there is way to retrieve the data in descending order but order must starts from the episode id 'epId'
I have tried the above method but failed
ViewBag.LoadEps = db.VideoEpisode
.Where(ve => ve.VideoId == id && ve.IsActive == true)
.OrderBy(c=>c.Sequence)
.First(c=> c.VideoEpisodeId ==epId);
EDIT: If I understand the problem correctly, you want the order to be a given episode with Id epId first, then a list ordered by sequence.
I'm not sure it can be done in one Linq query.
How about creating a new list, putting your chosen VideoEpisode in as the first element, and then appending a sorted list of the other episodes after that. Something like:
var Loadeps = new List<VideoEpisode>();
Loadeps.Add(db.VideoEpisode.First(c=> c.VideoEpisodeId ==epId));
Loadeps.Add(db.VideoEpisode
.Where(ve => ve.VideoId == id && ve.IsActive == true && c.VideoEpisodeId != epId)
.OrderByDescending(c => c.Sequence)).toList();

Filter condition not working properly on list (C#3.0)

I have a datatable that has many NULL or " " strings. Next I am type casting the DataTable to a list .
Now if I want to filter those conditions on this list and get the resultant value(without NULL or String.Empty or " " records) what should I do?
My code
DataTableExtensions.AsEnumerable(dt).ToList().ForEach(i =>
{
if (i[0] != null)
{
if ((i[0].ToString() != string.Empty)|| (i[0].ToString() != " "))
{
list = dt.AsEnumerable().ToList();
}
}
});
But I am getting all the records. It is not getting filtered.
Using C#3.0
Please help
Thanks
You're looking at i[0] so I'm going to assume that you're only interested in the first column of your table:
var rows = dt.AsEnumerable()
.Where(r => !r.IsNull(0) // check for DBNull
&& r[0] != null
&& r[0].ToString().Trim().Length > 0)
.ToList();
So that looks at every row but only returns the rows where the first column has a value and the string value is not empty or whitespace.