Copyright notice: This article is originally published BY CSDN blogger “Koader” under the CC 4.0 BY-SA copyright agreement. Please attach the link of the original source and this statement. Original link: blog.csdn.net/qq_24296235…

The first thing to remember is that the backend needs cross-domain configuration, especially for debugging.

One, simple implementation

1. HTML package, HttpRequest class.

var req = html.HttpRequest(); Req. setRequestHeaders(String key,String value)// Set custom header req.open(' POST ', 'URL '); Req.onloadend.listen ((event) {// here is the code block triggered when the response is received, can be passed directly from the external callback method ————Function class}); req.send('data'); // Send dataCopy the code

2. HTTP package, to add a dependency in pubspec.yaml, HTTP.

var req = Request('post', Uri.parse('url')); req.body=''; // Pass in the string // req.bodybytes =; You can pass in a byte array of type List<int> req.headers. AddAll (headers); Headers.send(). Then ((value) => null);Copy the code

3. Dio framework, to add dependencies in PubSpec, YAML.

Simple Usage Example

static Future<Response> register(String username,String password) async{
    try{
      return await Dio().post(Url,data:             
                              {'username':username,'password':password});//Map or String
    }catch(e){
      print(e);
      return null;
    }
}
Copy the code

Personally, I recommend using the third method, because Dio is already a better framework for packaging and is much easier to use than HTTP.

Second, the BaseOptions

A class provided by the Dio framework that wraps information such as request methods and custom headers in it for repeated use, passing in as arguments when constructing dio objects. With options with baseUrl, dio only needs to pass in the rest of the overall URL when sending a request.

static BaseOptions _options = BaseOptions(
    method: "get",
    baseUrl: _baseUrl,
    headers: {
    "token":_token,
    });
Copy the code
var dio = Dio(_options); _options.headers[key]=value; // You can set headers directlyCopy the code

3. Example of uploading data in form-data format

try{
      FormData formData = FormData.fromMap({
        'username':username,
        'password':password,
        'timer':timer
      });
      var dio = Dio();
      return await dio.post("url",data: formData).timeout(Duration(seconds: 3));
    }catch(e){
      print(e);
      return null;
    }
Copy the code

Timeout: Sets the timeout.

Readers are welcome to post questions in the comments section.