1
votes

I am learning front-end development in general with Angular Dart for a personal project (I've just learned back-end development with Django.) I get easily confused with the HTTP tutorial because from my perspective as a web developer beginner it tries to do a lot of things at the same time in different files or places and all related just for one purpose (it might be efficient to code that way, but I find hard learning from it.) I created an API for the project, and I want to know how to make a simple HTTP get request to build from there.

This is the JSON object that I'm trying to display:

"kanji": "老",
"onyomi": "ロウ",
"kunyomi": "お.いる、ふ.ける",
"nanori": "えび, おい, び",
"rtk_keyword": "old man",
"english": "old man, old age, grow old",
"jlpt": 3,
"jouyou_grade": "4",
"frequency": 803,
"radicals": [
    2555,
    2613
],
"pk": 1267

And this is my failed attempt at getting to display that data:

import "dart:async";
import 'dart:convert';

import 'package:angular2/angular2.dart';
import 'package:http/http.dart' as http;
import 'package:http/http.dart';


@Component (
  selector: "test",
  template: """
    <button (click)="change_info()">{{info}}</button>
    """,
)
class Test {
  String info = "default info";
  String _url = 'localhost:8000/kanji_detail/老';

  String get_and_decode(String url) {
    String data_to_return;
    http.get(url).then((response) => data_to_return = JSON.decode(response.body));
    return data_to_return;
  }

  String get_and_decode_long(String url) {
    Response request_response;
    Future request_future;
    String data_to_return;
    request_future = get(url);
    request_future.then((response) => request_response = response);
    data_to_return = JSON.decode(request_response.body);
    return data_to_return;
  }

  change_info() {
    info = get_and_decode_long(_url);
  }

}

the get_and_decode_long is me understanding that a Future and a Response are involved in this process, it wasn't very obvious.

1

1 Answers

4
votes
Future<String> get_and_decode(String url) async {
  var response = await http.get(url);
  return JSON.decode(response.body));
}

There is no way to get back from async to sync execution. async / await makes it quite easy to woek with async code though.

In your example return data_to_return; is executed before the response arrives.

See also