-1

With the new update, some HTTP functionality has changed. This function used to work and now it does not. Can someone explain what changed?

import 'package:http/http.dart';

    void getData() async {
    Response response = await get('https://jsonplaceholder.typicode.com/todos/1');
    Map data = JsonDecode(responce.body);
    print(data);
    }

lib/pages/loading.dart:24:37: Error: The argument type 'String' can't be assigned to the parameter type 'Uri'.
 - 'Uri' is from 'dart:core'.
      Response response = await get('https://jsonplaceholder.typicode.com/todos/1');
Korupt
  • 11
  • 2

1 Answers1

0

You can try this:

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

void getData() async {
  var response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/todos/1'));
  var data = jsonDecode(response.body) as Map;
  print(data);
}

UPDATE: Inserting code for WorldTimeApi

NetService:

class NetService {
  static Future<T?> getJson<T>(String url, {int okCode = 200}) {
    return http.get(Uri.parse(url))
      .then((response) {
        if (response.statusCode == okCode) {
          return jsonDecode(response.body) as T;
        }
        PrintService.showDataNotOK(response);
        return null;
      })
      .catchError((err) => PrintService.showError(err));
  }
}

Main:

import 'dart:async';

import 'package:_samples2/networking.dart';

class WorldTimeApi {
  static const _url = 'http://worldtimeapi.org/api/timezone';

  static FutureOr<void> fetchTime(String relPath) async {
    await NetService.getJson(_url + relPath)
      .then((response) => print(response))
      .whenComplete(() => print('\nFetching done!'));
  }
}

void main(List<String> args) async {
  await WorldTimeApi.fetchTime('/America/Los_Angeles');
  print('Done!');
}

Result:

{abbreviation: PST, client_ip: 179.6.56.125, datetime: 2021-03-09T17:24:09.367903-08:00, day_of_week: 2, day_of_year: 68, dst: false, dst_from: null, dst_offset: 0, dst_until: null, raw_offset: -28800, timezone: America/Los_Angeles, unixtime: 1615339449, utc_datetime: 2021-03-10T01:24:09.367903+00:00, utc_offset: -08:00, week_number: 10}

Fetching done!
Done!
  • Thank you. I was able to get it running by parsing the Uri. Just unsure why the first code sample used to work but now does not. Maybe you can help me with a second issue. if I use a https link for example var response = await http.get(Uri.parse('http://worldtimeapi.org/timezone/America/Los_Angeles')); I get this error message: flutter: Bad state: Insecure HTTP is not allowed by platform: What is the ideal way to handle nonsecure links? – Korupt Mar 10 '21 at 00:09
  • I don't know how you will be coding, but `http` works fine for me. I've inserted my code above. – Ουιλιαμ Αρκευα Mar 10 '21 at 01:28