'dart's http request in future function returns null

I am trying to get data from the website

void main() async {
  var resp = await http.get(
    Uri.parse('https://m.example.com/example'),
    headers: {
      'User-Agent':
          'Mozilla/5.0 (iPhone; CPU iPhone OS 12_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148'
    },
  );
  print(resp.body);
}

But when I wrap this code into a function, the resp returns null

Future getLiveHtml(String url) async {
  var resp = await http.get(
    Uri.parse(url),
    headers: {
      'User-Agent':
          'Mozilla/5.0 (iPhone; CPU iPhone OS 12_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148'
    },
  );
  return resp.body;
}

how to fix it?



Solution 1:[1]

You should specify the type you return in method Future<String> description like that:

library shfl;

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

static Future<String> getLiveHtml(String url) async {
  var resp = await http.get(
    Uri.parse(url),
    headers: {
      'User-Agent':
          'Mozilla/5.0 (iPhone; CPU iPhone OS 12_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148'
    },
  );
  return resp.body;
}

and then call it in async function with await statement like that:

import 'package:flutter_test/flutter_test.dart';

import 'package:shfl/shfl.dart';

void main() {
  test('prints html from google', () async {
    var rez = await Stuff.getLiveHtml("https://google.com/");
    print(rez);
  });
}

Solution 2:[2]

what version of the http package are you using for your project?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Danila Fominyh
Solution 2 nonsocchi