Dart is too fast - dart

I'm trying to understand why this code print "check" twice...
import 'dart:io';
import 'dart:async';
import 'dart:convert';
Future<Map> ft_get_data() {
File data;
data = new File("data.json");
return data.exists().then((value) {
if (!value) {
print("Data does no exist...\nCreating file...");
data.createSync();
print("Filling it...");
data.openWrite().write('{"index":{"content":"Helllo"}}');
print("Operation finish");
}
}).then((_) => data.readAsString()).then((content) => JSON.decode(content)
).catchError((e) => new Map());
}
void main() {
Map params;
String name;
num check = 0;
HttpServer.bind('127.0.0.1', 8080).then((server) {
print("Server is lauching... $server");
server.listen((HttpRequest request) {
request.response.statusCode = HttpStatus.ACCEPTED;
request.response.headers.contentType = new ContentType('text', 'htm l');
params = request.uri.queryParameters; // http://127.0.0.1:8080/?name=tristan
ft_get_data().then((data_map) {
name = data_map['index']['content'];
print('check: $check');
if (data_map.isNotEmpty) request.response.write(name); else
request.response.write('Booh');
check++;
}).whenComplete(request.response.close);
});
}).catchError((error) {
print("An error : $error.");
});
}
Is it too fast ? Or there exist some method to make a pause ? Thank you.

I tried your code and it prints 0.
What client are you using to access the server?

Related

Why can't catch exceptions with "catchError" in Dart?

Test:
void testAs() async {
try {
String b = await test();
print(b);
} catch (e) {
print("1 await error");
}
test().then((value) => print(value)).catchError(() {
print("2 then error");
});
}
Future<String> test() {
List<String> bb = ["2222"];
return Future.value(bb[1]);
}
1 await error
RangeError (index): Invalid value: Only valid value is 0: 1
Why is it ineffective?
If I want to deal with "future" through "then", how should I catch the exception and not let it throw out.
Thank you friends,the last problem has been solved,the problem can be solved by adding async and await flags to the test() method.
But there is a new problem, Now I use the correct code and find that it can only be printed once.why can't it print "then success",then the program ends
,modify as follows:
void testAs() async {
try {
await test();
print("await success");
} catch (e) {
print("await error");
}
test().then((value) => print("then success")).catchError((e) {
print("then error");
});
}
Future<String> test() async{
List<String> bb = ["2222"];
return await Future.value(bb[0]);
}
print:await success

How can I tell if a string can be json.decode

My cache class
import 'dart:async';
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
class CacheUtil{
static set(String key, value) async{
if(value is Map || value is List){
value = json.encode(value);
}
SharedPreferences preferences = await SharedPreferences.getInstance();
preferences.setString(key, json.encode(value));
}
static get(String key) async{
SharedPreferences preferences = await SharedPreferences.getInstance();
String data = preferences.getString(key);
return data;
}
}
In the get method ,I want to see if value can be json.decode
what should I do?
Just try to decode it and catch FormatException to know when it failed:
void main() {
var jsonString = '{"abc';
var decodeSucceeded = false;
try {
var decodedJSON = json.decode(jsonString) as Map<String, dynamic>;
decodeSucceeded = true;
} on FormatException catch (e) {
print('The provided string is not valid JSON');
}
print('Decoding succeeded: $decodeSucceeded');
}
I like something that looks like int.tryParse(data).
So I using this.
import 'dart:convert';
class Json {
static String? tryEncode(data) {
try {
return jsonEncode(data);
} catch (e) {
return null;
}
}
static dynamic tryDecode(data) {
try {
return jsonDecode(data);
} catch (e) {
return null;
}
}
}
Using like this.
void main() {
String? jsonEncode = Json.tryEncode(dataEncoded);
if (jsonEncode == null) {
print("jsonEncode is null");
} else {
print("jsonEncode is not null");
}
dynamic jsonDecode = Json.tryDecode(dataDecoded);
if (jsonDecode == null) {
print("jsonDecode is null");
} else {
print("jsonDecode is not null");
}
}
Caution: When you use Json.tryDecode( jsonEncode(null) ) that function can't tell you if this can convert to JSON or not because the result always is null. But I don't worry about this.

Dart Language: GET (favicon issue)

I have a Dart application running on the server side. It is listening at a specific port and working fine. The problem is: my listener is responding to the GET of the favorite icon (favicon).
How can I avoid that?
EDIT: give some code example.
import 'dart:io';
void main() {
print("Starting server.");
HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 4041)
.then(listenForRequests)
.catchError((e) => print (e.toString()));
}
listenForRequests(HttpServer _server) {
_server.listen((HttpRequest request) {
if (request.method == 'GET') {
handleGet(request);
} else {
request.response.statusCode = HttpStatus.METHOD_NOT_ALLOWED;
request.response.write("Unsupported request: ${request.method}.");
request.response.close();
}
},
onDone: () => print('No more requests.'),
onError: (e) => print(e.toString()) );
}
void handleGet(HttpRequest request) {
int requestNumber = 1;
print(requestNumber); // This shows me the request number. Just for information.
print(request.uri); // This shows me the request from the client browser.
request.response.statusCode = HttpStatus.OK;
request.response.close();
}
This is the output of this code:
1
/SOME_REQUEST_FROM_THE_BROWSER
2
/favicon.ico
You can check the requested resource and generate proper response for requests to 'favicon.ico' like
void handleGet(HttpRequest request) {
int requestNumber = 1;
print(requestNumber++); // This shows me the request number.
print(request.uri); // This shows me the request from the client browser.
if(request.requestedUri.path != '/favicon.ico') {
request.response.statusCode = HttpStatus.NOT_FOUND;
} else {
request.response.statusCode = HttpStatus.OK;
}
request.response.close();
}

Dart HTTPClient Response query

I would like to make the below functionality synchronous. The "onDataLoaded" needs to be called once the stream has been read completely. Please suggest what changes needs to be done.
String JsonContent="";
new HttpClient().getUrl(Uri.parse(uri))
.then((HttpClientRequest request)
{
request.headers.removeAll(HttpHeaders.ACCEPT_ENCODING);
return request.close();
})
.then((HttpClientResponse response)
{
response.transform(UTF8.decoder).listen((contents) {
JsonContent = contents.toString();
print(JsonContent);
//onDataLoaded(JsonContent);
});
});
this should work
import 'dart:io';
import 'dart:convert' show UTF8;
void main(args) {
String JsonContent="";
new HttpClient().getUrl(Uri.parse(uri))
.then((HttpClientRequest request)
{
request.headers.removeAll(HttpHeaders.ACCEPT_ENCODING);
return request.close();
})
.then((HttpClientResponse response)
{
response.transform(UTF8.decoder).listen((contents) {
JsonContent = contents.toString();
print(JsonContent);
//onDataLoaded(JsonContent);
}, onDone: () => onDataLoaded(JsonContent));
});
}
void onDataLoaded(String jsonContent) {
print(jsonContent);
}

Dart get back value of function

I'm trying to learn Dart by my self, but I come from C and I a bit confused...
I'm doing this :
import 'dart:io';
import 'dart:async';
import 'dart:convert';
Future <Map> ft_get_data()
{
File data;
data = new File("data.json");
return data.exists().then((value) {
if (!value)
{
print("Data does no exist...\nCreating file...");
data.createSync();
print("Filling it...");
data.openWrite().write('{"index":{"content":"Helllo"}}');
print("Operation finish");
}
return (1);
}).then((value) {
data.readAsString().then((content){
return JSON.decode(content);
}).catchError((e) {
print("error");
return (new Map());
});
});
}
void main()
{
HttpServer.bind('127.0.0.1', 8080).then((server) {
print("Server is lauching... $server");
server.listen((HttpRequest request) {
request.response.statusCode = HttpStatus.ACCEPTED;
ft_get_data().then((data_map) {
if (data_map && data_map.isNotEmpty)
request.response.write(data_map['index']['content']);
else
request.response.write('Not work');
}).whenComplete(request.response.close);
});
}) .catchError((error) {
print("An error : $error.");
});
}
I'm trying to get back the new Map, and as you can guess, it doesn't work and I get the 'Not work' msg. While when the code was in same function, it worked...
Please, could you help me ?
And, there a pointer system as C ?
void function(int *i)
{
*i = 2;
}
int main()
{
int i = 1;
function(&i);
printf("%d", i);
}
// Output is 2.
Thank you for your help.
Final code :
import 'dart:io';
import 'dart:async';
import 'dart:convert';
Future<Map> ft_get_data()
{
File data;
data = new File("data.json");
return data.exists()
.then((value) {
if (!value) {
print("Data does no exist...\nCreating file...");
data.createSync();
print("Filling it...");
data.openWrite().write('{"index":{"content":"Helllo"}}');
print("Operation finish");
}
})
.then((_) => data.readAsString())
.then((content) => JSON.decode(content))
.catchError((e) => new Map());
}
void main()
{
HttpServer.bind('127.0.0.1', 8080)
.then((server) {
print("Server is lauching... $server");
server.listen((HttpRequest request) {
request.response.statusCode = HttpStatus.ACCEPTED;
ft_get_data()
.then((data_map) {
if (data_map.isNotEmpty)
request.response.write(data_map['index']['content']);
else
request.response.write('Not work');
})
.whenComplete(request.response.close);
});
})
.catchError((error) {
print("An error : $error.");
});
}
I tried to reconstruct your code to "readable" format. I haven't test it, so there might be errors. For me the code is much easier to read if .then() are not nested. Also it helps reading, if .then() starts a new line.
import 'dart:io';
import 'dart:async';
import 'dart:convert';
Future <Map>ft_get_data()
{
File data;
data = new File("data.json");
data.exists() //returns true or false
.then((value) { // value is true or false
if (!value) {
print("Data does no exist...\nCreating file...");
data.createSync();
print("Filling it...");
data.openWrite().write('{"index":{"content":"Helllo"}}');
print("Operation finish");
}
}) // this doesn't need to return anything
.then((_) => data.readAsString()) // '_' indicates that there is no input value, returns a string. This line can removed if you add return data.readAsString(); to the last line of previous function.
.then((content) => JSON.decode(content)); // returns decoded string, this is the output of ft_get_data()-function
// .catchError((e) { //I believe that these errors will show in main-function's error
// print("error");
// });
}
void main()
{
HttpServer.bind('127.0.0.1', 8080)
.then((server) {
print("Server is lauching... $server");
server.listen((HttpRequest request) {
request.response.statusCode = HttpStatus.ACCEPTED;
ft_get_data()
.then((data_map) {
if (data_map && data_map.isNotEmpty)
request.response.write(data_map['index']['content']);
else
request.response.write('Not work');
})
.whenComplete(request.response.close);
});
})
.catchError((error) {
print("An error : $error.");
});
}
you cannot insert one then() into the other. Need to chain them. Otherwise, return JSON.decode(data) returns to nowhere (main event loop) instead of previous "then" handler
After a brief look I would say you need
Future<Map> ft_get_data() {
...
return data.exists() ...
...
}
and use it like
server.listen((HttpRequest request) {
request.response.statusCode = HttpStatus.ACCEPTED;
ft_get_data().then((data_map) {
if (data_map && data_map.isNotEmpty) request.response.write(
data_map['index']['content']);
else
request.response.write('Not work');
request.response.close();
});
});
A return inside a then doesn't return from ft_get_data but only from then
If an async call is involved you can't continue if it was sync, it's then async all the way down.

Resources