How to cast an array from Firestore in dart - dart

I have a class
UserModel{
late final List<UserEmail> emails;
}
I trying to retrieve an array from Firestore.
UserModel.fromJson( emails = json[emailsKey] != null
? (json[emailsKey] as List<Map<String,dynamic>>).map((Map<String, dynamic> email) => UserEmail.fromJson(email)).toList()
: <UserEmail>[],
The emailsKey is the key to emails array in Firestore..
The error I'm getting back is
Failed: type 'List<dynamic>' is not a subtype of type 'List<Map<String, dynamic>>' in type cast<…>
I'm not sure why my casting isn't working (at runtime).
Any ideas

Try the following:
var temp = json[emailsKey];
List<String> emailKeys = List<String>.from(temp);

Related

is there a way to perform optional casting in Dart?

in Swift or Kotlin I can do something like this
var fullName = myMap["fullName"] as? String
then as a result that fullName data type will be optional String ( String? ).
I need to get optional type after type checking like that
I can't directly perform null coalescing operator to that map, because dart will give weird result. for example like this
// 'data' is Map<String, dynamic>
final fullName = data["fullname"] ?? "John Doe";
final double myNumber = fullName;
as you can see, the IDE will not show an error at all, I expect that fullName will be a String, so it will have an error when I assign a String to myNumber that require double.
If you know in advance that data["fullname"] is a String, then you could do:
final fullName = (data["fullname"] ?? "John Doe") as String;
If data["fullname"] turns out not to be a String at runtime, you'll get a runtime exception from the cast failure. If that's something you need to handle, then you could easily make a trivial helper function that checks if a dynamic value is the desired type first and that returns null if it isn't:
T? tryCast<T>(dynamic object) => object is T ? object : null;
final fullName = tryCast<String>(data["fullname"]) ?? "John Doe";
and now fullName is statically known to be a String, and accidentally assigning it to a double will be a compile-time error.
The safe nullable cast operator known from Kotlin currently doesn't exist in Dart but it soon might.
In your case though, why not simply write
String? fullname = myMap["fullname"];
The nullable cast operator as? in Kotlin yields null if myMap["fullname"] contains anything but a non-null String. As long as you're only dealing with Strings or null, the above works just fine. (And if there's anything but a String or null it crashes, which is probably better than just continue on with null in most situations)

Can't understand why this cast is invalid

I am a bit confused about why this casting am I performing is throwing an exception. This is the code:
var myJson = json.decode(response.body);
List<Map<String,dynamic>> childrenJson = myJson['children'] as List<Map<String,dynamic>>;
But this works as expected:
var myJson = json.decode(response.body);
List<dynamic> childrenJson = myJson['children'];
Map<String, dynamic> item = childrenJson[0];
If the children entry is a list of maps of (String, dynamic) why am I not able to cast it that way?
I think you'll want to use:
var childrenJson = List.cast<Map<String,dynamic>>(myJson['children]);
which should throw an exception at runtime if any of the children cannot be casted. The "as" is more of a compile-time thing, and can only be used if the compiler can infer that as a type.

GUID error - InvalidCastException: Unable to cast object of type 'System.Decimal' to type 'System.Int64'

I am using GUID identifiers to track certain activities in cookies and checking to see if it exists in the db, but I am getting the error
InvalidCastException: Unable to cast object of type 'System.Decimal' to type 'System.Int64'.
Here is my code
string Cookies2 = Request.Cookies["Upload_Guid"].ToString();
Guid Cookie_Guid = Guid.Parse(Cookies2);// GEt the value of cookie and parse it to a GUID
var GID_Variable = await _context.Upload_Transaction
.SingleOrDefaultAsync(m => m.Cookie_GUID == Cookie_Guid);
I found the problem, it had nothing to do with the code, apparently in my database, I had a field which was image size (Int) and in my code, it was Long, so I changed it from Int to BigInt and its ok now
Hence the error here
var GID_Variable = await _context.Upload_Transaction
.SingleOrDefaultAsync(m => m.Cookie_GUID == Cookie_Guid);
Although the code does not show the size field
thanks

Cannot subsript a value of type anyobject in swift 2

I am migrating to swift 2.0 I was using following code well. But I am getting errors in swift 2.
SRWebClient.POST("upload url")
.data(imageData, fieldName:"image_field", data: ["username":"username","key":"test"])
.send({(response:AnyObject!, status:Int) -> Void in
if status == 200 {
var s_status=response?["status"] as! Int
...
I am getting following error for var s_status line.
Cannot subscript a value of type 'AnyObject!' with an index of type 'String'
How can I fix it?
The error is telling you that you can't use ["status"] on an object of type AnyObject, because it may not work if it's not a dictionary. You need to convert response to a Dictionary first.
I see you're using SRWebClient, which I've never used, but according to their github this seems safe:
let responseJSON = response! as Dictionary<String, String>
I'm guessing they serialize in their code first. I dunno though... I'd make sure that object was a Dictionary before forcing a cast.

LINQ Checking for Nulls

How do I check Nulls in Linq?
I have a third-party code that returns a DataTable with a column type DateTime that is nullable.
My code:
var profile = (from d in ds.Tables[0].AsEnumerable()
select new User
{
FirstName = d["FirstName"].ToString(),
Birthdate = Convert.ToDateTime(d["BirthDate"].ToString())
}).FirstOrDefault();
returns an error that the Object cannot be cast from DBNull to other types on the Birthdate= statement.
I tried using the following code but returns a cast exception (Cannot cast from string to DateTime?)
Birthdate = (DateTime?)d["BirthDate"].ToString();
Is there a way to short-hand checking the null values?
I have not tested this, but you can try the following:
Birthdate = d.Field<DateTime?>("BirthDate")
From MSDN:
The Field method provides support for accessing columns as nullable types. If the underlying value in the DataSet is [DBNull.]Value, the returned nullable type will have a value of null.
You can create a helper function to check the value for DBNull, as follows:
private static DateTime? ConvertNullableToDateTime(object val) {
return (val != null && val != DBNull.Value) ? Convert.ToDateTime(val.ToString()) : null;
}
Now you can use this method in your LINQ query:
var profile = (from d in ds.Tables[0].AsEnumerable()
select new User
{
FirstName = d["FirstName"].ToString(),
Birthdate = ConvertNullableToDateTime(d["BirthDate"])
}).FirstOrDefault();
I have got error while I used the above code. I think we can use the below code.
Birthdate = dr["BirthDate"] == DBNull.Value ? (DateTime?)null : (DateTime)dr["BirthDate"];
If we use Convert.ToString(dr["BirthDate"]), then it convert to empty string, if it has DBNull.
Try that also.

Resources