I'm new to Dart and was wondering over how the .cast() method works with dynamic types and lists.
This is a working example from the Flutter documentation on how to parse JSON manually in Dart:
List<Photo> parsePhotos(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}
where responseBody is some JSON array previously fetched from a HTTP endpoint.
I don't understand why the result of json.decode(responseBody) is cast to Map<String, dynamic> when logically it should be List<Map<String, dynamic>>. I've debugged the code and in fact the variable parsed is a list subtype.
What am I getting wrong here?
Thanks in advance.
It looks like it is correct. cast is a method of Iterable. The type in angle brackets is the type of each element in the iterable.
https://api.dart.dev/stable/2.7.1/dart-core/Iterable/cast.html
aye aye good people,
I'm really confused about the behavior of DateTime.parse();
on dartpad this works
void main() {
const String _iso8601 = '2019-04-01T08:30:00';
final DateTime _date = DateTime.parse(_iso8601);
print(_date.toIso8601String());
}
but in flutter doesn't, but this does
const String _iso8601 = '2019-04-01T08:30:00.000';
final DateTime _date = DateTime.parse(_iso8601);
I'm now in aqueduct and neither of those works including this
String _iso8601 = '2019-04-01T08:30:00Z';
please note that with "didn't work" I don't mean that it returns an error,
but just a null.
[edit: correction
when I mock the string instead of mapping it from the body of a request it returns
Exception has occurred. FormatException (null)
but then again I'm using Iso8601]
If you have some experience with this situation I could use some help.
[edit: note that aqueduct runs on dart 2.0]
Thank you in advance, Francesco
Examples of accepted strings:
"2012-02-27 13:27:00"
"2012-02-27 13:27:00.123456z"
"2012-02-27 13:27:00,123456z"
"20120227 13:27:00"
"20120227T132700"
"20120227"
"+20120227"
"2012-02-27T14Z"
"2012-02-27T14+00:00"
"-123450101 00:00:00 Z": in the year -12345.
"2002-02-27T14:00:00-0500": Same as "2002-02-27T19:00:00Z"
Getting error while parsing string to datetime.
string datestring = "111815";
DateTime date = Convert.ToDateTime(datestring);
I also tried using, Parse, ExactParse with/without culture specificinfo.
I'm still getting the error:
String was not recognized as a valid DateTime.
Please suggest the correct solution.
You just need to specify the right format string when you call ParseExact. In your case, it looks like this is month-day-year, without any separators, and with a 2-digit year (blech). So you'd parse it like this:
using System;
using System.Globalization;
class Test
{
static void Main()
{
DateTime dt = DateTime.ParseExact("111815", "MMddyy", CultureInfo.InvariantCulture);
Console.WriteLine(dt);
}
}
If you're in control of the format at all, I'd strongly recommend yyyy-MM-dd instead of this ambiguous (due to the 2-digit years) and US-centric (due to month/day/year) format.
I'm trying to render command validation errors as json but I'm getting an exception. The command object is using joda time DateTime objects instead of java.util Date objects. The code to do the json rendering looks like:
def results = eventSaleDataCommand.errors.fieldErrors.toList()
def errors = []
for (error in results) {
errors.add([
'type' : 'invalid_entry',
'field' : error.field,
'rejected_value': error.rejectedValue,
'message' : error.defaultMessage
])
}
render errors as JSON
The exception I'm getting is:
Class org.codehaus.groovy.grails.web.converters.marshaller.json.GenericJavaBeanMarshaller can not access a member of class org.joda.time.tz.DateTimeZoneBuilder$PrecalculatedZone with modifiers "public".
Anyone know how to get around this?
Implementing a Joda converter did the trick. Thanks.
I'd like my Dart program to print to the dev console of my browser. How can I print to the console (DevTools's console, for example) ?
Use print() to print a string to the console of your browser:
import 'dart:html';
main() {
var value = querySelector('input').value;
print('The value of the input is: $value');
}
You will see a message printed to the developer console.
If you simlpy want to print text to the console you can use print('Text').
But if you want to access the advanced fatures of the DevTools console you need to use the Console class from dart:html: Console.log('Text').
It supports printing on different levels (info, warn, error, debug). It also allows to print tables and other more advanced features. Note that these are not supported in every browser! It's sad that the documentation about the Console class is incomplete, but you can take a look at the documentation of Chrome here and here.
There is log() from import 'dart:developer' library also.
example:
int name = "Something";
log("ClassName: successfully initialized: $name");
//output
[log] ClassName: successfully initialized: Something
Please note that log and debugPrint taking a value of String not like print. So, you have to add .toString() at the end or use with String interpolation like I used in above example.
From doc:
You have two options for logging for your application. The first is to
use stdout and stderr. Generally, this is done using print()
statements, or by importing dart:io and invoking methods on stderr and
stdout. For example:
stderr.writeln('print me');
If you output too much at once, then Android sometimes discards some
log lines. To avoid this, use debugPrint(), from Flutter’s foundation
library. This is a wrapper around print that throttles the output to a
level that avoids being dropped by Android’s kernel.
The other option for application logging is to use the dart:developer
log() function. This allows you to include a bit more granularity and
information in the logging output. Here’s an example:
import 'dart:developer' as developer;
void main() {
developer.log('log me', name: 'my.app.category');
developer.log('log me 1', name: 'my.other.category');
developer.log('log me 2', name: 'my.other.category');
}
You can also pass application data to the log call. The convention for
this is to use the error: named parameter on the log() call, JSON
encode the object you want to send, and pass the encoded string to the
error parameter.
import 'dart:convert'; import 'dart:developer' as developer;
void main() {
var myCustomObject = ...;
developer.log(
'log me',
name: 'my.app.category',
error: jsonEncode(myCustomObject),
);
}
If viewing the logging output in DevTool’s logging view, the JSON
encoded error param is interpreted as a data object and rendered in
the details view for that log entry.
read more(It's cool like a tutorial).
If you are here for Flutter, there's debugPrint which you should use.
Here's the doc text for the same.
/// Prints a message to the console, which you can access using the "flutter"
/// tool's "logs" command ("flutter logs").
/// By default, this function very crudely attempts to throttle the rate at
/// which messages are sent to avoid data loss on Android. This means that
/// interleaving calls to this function (directly or indirectly via, e.g.,
/// [debugDumpRenderTree] or [debugDumpApp]) and to the Dart [print] method can
/// result in out-of-order messages in the logs.
You might get SDK version constraint as it is only for 2.2 and above.
Dart print() function works differently in different environment.
print() when used in console based application it outputs in the terminal console
print() when used in web based application it outputs to the developer console.
void main() {
print("HTML WebApp");
}
The only way I know , which is supported by dartpad ,is through using print();
by the way Dart uses the ${} syntax for expressions, or just a $ for single value.
ex:-
int x=3;
print('hello world') ;
print(x) ;
print('x = $x') ;
and her is the link for the documentation
print method!