Search code examples
dartdart-async

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.");
    });
}

Solution

  • 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.");
        });
    }