String to double from a map in Dart - flutter

Ive tried to use double.parse, double.tryparse as well as trying to convert it to int but it keeps giving the error 'type 'int' is not a subtype of type 'String'', ive searched a few sites but all the solutions show to use parse.
final locData = Map<String, dynamic>.from(local);
var dubLat = locData['lat'];
var lat = double.tryParse(dubLat);
ive tried changing var to double nit still give the same error.

The .tryParse takes a string or even the parse method for this instance takes a string. But your data is actually integers therefore the error type int is not a subtype of type string. You should consider either storing them as ints or using the .toString method before parsing them.
var dubLat = locData['lat']; // Here dublat is not actually a string but integer. Your map has dynamic as a second parameter it can take all data types and this particular datatype is int not string which .parse expects.
var lat = double.tryParse(dubLat.toString());

You are facing this error because you are trying to pass int but double.tryParse need string value that's why getting this error 'type 'int' is not a subtype of type 'String'
I solved by this 'double.tryParse(dubLat.toString());'
final locData = Map<String, dynamic>.from(local);
var dubLat = locData['lat'];
var lat = double.tryParse(dubLat.toString());

Related

type 'String' is not a subtype of type 'DateTime'

I tried calling this code:
var test = int.parse(DateFormat('yyyy').format(formattedTemporaryDate));
but I get the error:
type 'String' is not a subtype of type 'DateTime'
my formattedTemporaryDate is '2022-01-08'
I think I need to transform the formattedTemporaryDate to an int, but I don't know how. And I even don't know if this really is the problem... Do you need more information to fix my problem?
Just use DateTime.parse('2022-01-08') instead of just String.
Something like var formattedTemporaryDate = DateTime.parse('2022-01-08');
What would you like var test to be at the end? A datetime? An int representation of the date?
You can convert your string to a DateTime object by calling DateTime.parse()
var formattedTemporaryDate = '2022-01-08';
DateTime dt = DateTime.parse(formattedTemporaryDate);
print(dt); // 2022-01-08 00:00:00.000
If you then want to convert it to an Int (maybe because you're doing UNIX Timestamp stuff?) You could try reverse-engineering some of the code people added here going the other direction.

What is the difference between a `String x = expr` and `var x = expr as String`?

While developing a Flutter app, I ran into a problem where out of two seemingly similar things, only one really works. The other gives an error.
// this does NOT work
// gives error: E/flutter (13080): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception:
// type 'MaterialPageRoute<dynamic>' is not a subtype of type 'Route<String>?' in type cast
onButtonPress() async {
String ret = await Navigator.of(context).pushNamed("/page");
print(ret);
}
// this works !
onButtonPress() async {
var ret = await Navigator.of(context).pushNamed("/page") as String;
print(ret);
}
Both looks like doing the same thing - casting the value returned from the route into a String. But why does only one of them works ?
As your error states:
// gives error: E/flutter (13080): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception:
// type 'MaterialPageRoute<dynamic>' is not a subtype of type 'Route<String>?' in type cast
onButtonPress() async {
String ret = await Navigator.of(context).pushNamed("/page");
print(ret);
}
You are trying to assign a MaterialPageRoute<dynamic!> to a Route<String!>.
This is a simple case of type mismatching.
In the other example that you have posted, you are using var instead of String. This allows you to assign every type that you want to it.
await Navigator.of(context).pushNamed("/page") returns a future, which is not a string.
the scope of a var is just a generic variable that can be anything upon assignation.
When you assign a variable as String X , that means you tell the program specifically that - I am sure that the value I am going to get will be String and I want it to be stored in X . If the value returned is not String type it will throw an error.
When you assign the variable as var X , that means you are telling the program that I am not sure what will be the type of value which will be returned but I want the returned value to be returned as 'String ' (so even if you get any response as int or double or anything else it will try to use the complete value returned as string) . So var helps in getting rid of type errors when you are not sure of the type , but it's always best practice to know what type you are getting and define accordingly.

Not able to downcast a dynamic to a List<int> when used on a Map

Let's start with:
dynamic list = [1];
var ints = list as List<int>; // Works
I am downcasting dynamic typed list to a type of List<int> and it works. Now, let's take another example:
var jsonString = '{"0": [1]}';
var Map<String, dynamic> map = jsonDecode(jsonString);
dynamic list = map['0'];
var ints = list as List<int>; // Fails
This time I am doing the same thing, list is of type dynamic and I'm downcasting it to List<int> but it fails with an error:
'List<dynamic>' is not a subtype of type 'List<int>' in type cast.
Can anyone tell me why first code works but second fails?
Note: I am not looking for a solution on how to make 2nd code work, I know how to do that. The question is in 1st code dynamic can be downcasted to List<int> but in second it can't be. Why is that so?
Can anyone tell me why first code works but second fails?
The first code, you already have a List<int> (or maybe a JsArray<int> that implements List<int>). So typecasting works.
The second code, you do not have a List<int>. You have a JsArray<dynamic> that implements List<dynamic>. But that cannot be typecast into a List<int>. Because it simply isn't.
If you want to know why a List<dynamic> is not a List<int>, think of it that way: a List of animals is not a list of wolves. There could be sheep in it, too. If you want to have a list of wolves, you will have to convert the original list, not just typecast it.
Try and see which types you're getting by printing the runtimeType
dynamic list = [1];
print(list.runtimeType);
var ints = list as List<int>; // Works
And
var jsonString = '{"0": [1]}';
var Map<String, dynamic> map = jsonDecode(jsonString);
dynamic list = map['0'];
print(list.runtimeType);
var ints = list as List<int>; // Fails
But it has probably to do with [1] being recognised as a List<int> which obviously can be casted to List<int>. But because your map is <String, dynamic> it could be any type in map['0'] and that cannot be casted.
You could always make it work by using List.from()
List<int> ints = List.from(map['0']);
https://api.dart.dev/stable/2.9.1/dart-core/List/List.from.html

Swift - Binary operator '>=' cannot be applied to operands of type 'String' and 'Int'

Not really understanding why this isn't working. I'm pretty new to the Swift world.
The error I'm getting is Binary operator '>=' cannot be applied to operands of type 'String' and 'Int'
Could anyone help me understand why I'm getting this error? Do I need to convert the String to a Double or is there something else I'm totally missing? Again I'm new to Swift.
Do I need to convert the String to a Double?
Yes, that's basically it.
You must declare first a variable to accumulate all the inputs:
var inputs = [Double]()
Observe that I'm declaring an array of Double because that's what we are interested in.
Then, each time you ask the input, convert the obtained String to Double and store it in your array:
print("Please enter a temperature\t", terminator: "")
var message : String = readLine()!
let value : Double = Double(message)!
inputs.append(value)
Finally, check all the accumulated values in inputs (you got this part right):
for value in inputs {
// value is already a Double
if value >= 80 {
message = "hot!"
}
// etc.
}
I suggest researching how to convert to Double with error checking (i.e. how to detect "100 hot!" and ignore it because can't be converted).
Also, consider using a loop to read the values.

cannot convert from 'out double?' to 'out double'

I have the following section of code in an app that I am writing:
...
String[] Columns = Regex.Split(CurrentLine, Delimeter);
Nullable<Double> AltFrom;
...
if (AltFrom == null)
{
Double.TryParse(Columns[LatIndex].Trim(), out AltFrom);
}
...
The line in the if clause will not compile and shows the error: cannot convert from 'out double?' to 'out double'
if I don't make AltFrom a Nullable type and rather explicitly state it as a Double, everything is happy.
Surely this is valid code. Is this just a bug in c# or am I doing something wrong?
No the out parameter really needs to be a double, not a Nullable<double>.
double? altFrom = null;
double temp = 0;
if (double.TryParse( Columns[LatIndex].Trim(), out temp))
{
altFrom = temp;
}
First, you can not implicitly convert a double? to a double. The reason is because what would be the value of the double if the double? represented the null value (i.e., value.HasValue is false)? That is, converting from a double? to a double results in a loss of information (it is a narrowing conversion). Implicit narrowing conversions are generally frowned upon in the framework.
But actually, the problem that you are seeing here is something different. When you have a method that accepts an out parameter of type T, you must pass in a variable of type T; there can not be any type variation in this case as there is with non-ref and non-out parameters.
To get around your problem, use the following:
if (AltFrom == null) {
double value;
Double.TryParse(Columns[LatIndex].Trim(), out value);
AltFrom = value;
}