Dart get back value of function - dart

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.

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

Flutter dart function skipping to end of function after await

I have a function with the keyword async and after the await is done, it skips a bunch of lines of codes and goes to the end of the function after the await is done. Does anyone know what I am doing wrong?
void _createNewGroup(Function createNewGroup, BuildContext context) async {
if (_validateAndSave()) {
try {
print("trying");
Map<String, dynamic> result = await createNewGroup(_group_name);
print("sucess is $result");
if (result['success']) {
print('Success poping dialoge');
Navigator.of(context).pop();
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => HomePage()));
} else {
print("not created group");
}
} catch (error) {}
}
}
Future<Map<String, dynamic>> createNewGroup(String name) async {
var result = {};
var response;
print('Group name $name');
print("creating group");
var group = ParseObject('Groups')
..set("group_name", name)
..set('createdBy_name', _parseUser.get('first_name'))
..set('CreatedBy_id', _parseUser.objectId)
..set('members', [{'name': _parseUser.get('first_name'), 'id': _parseUser.objectId}]);
response = await group.save();
if(response.success) {
print('sucess creating object');
result = {'success': true, 'message': 'New Group Created'};
return result;
} else {
result = {'success': false, 'message': 'Error occured creating group'};
}
print("result is $result");
print("response is ${response.result}");
return result;
}

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 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 is too fast

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?

Resources