Home > Net >  dart's http request in future function returns null
dart's http request in future function returns null

Time:03-13

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?

CodePudding user response:

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

CodePudding user response:

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

  • Related