Flutter incorporates HTTP request objects that are extremely simple to use. Find a debugging tool to try HTTP requests today. For more information, check out the official API DART: IO, which is listed on the right.
The first step is to go to a website with a free HTTP request API, such as aggregating data to query the weather, register an account, and then apply for this free API. Of course, you can also apply for other free apis, for example, I applied for two free apis:
Step 2 Open VScode, go to the terminal to find a directory where the project code is stored, and enter the command:
flutter create myhttptest
After the project folder is initialized, open the project folder with VScode -> open main.dart and override the initialized code with the following code:
import 'dart:convert'; Import 'dart: IO '; / / integration File, socket, HTTP services such as application of IO library import 'package: flutter/material. The dart'; void main() { runApp(new MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( home: new MyHomePage(), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key}) : super(key: key); @override _MyHomePageState createState() => new _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { var _ipAddress = 'Unknown'; // Why do we define this variable? _getIPAddress() async {/* interface url Contains the request address http://op.juhe.cn/onebox/weather/query and two parameters cityname, AppKey * / var url = Shanghai & key = 'http://op.juhe.cn/onebox/weather/query?cityname= [replace your AppKey]'. var httpClient = new HttpClient(); String result; Var request = await httpClient.posturl (uri.parse (url)); */ var response = await request.close(); */ var response = await request.close(); if (response.statusCode == HttpStatus.OK) { var json = await response.transform(UTF8.decoder).join(); var data = JSON.decode(json); result = data['result']['data']['realtime'].toString(); } else {result = 'Error get:\nHttp status ${response.statuscode}'; }} catch (exception) {result = 'Failed getting data'; } // If the control is deregistered, the built-in state of the control is Mounted. /* If the network is stuck and the current control is logged out for some other reason, you do not need to call setState(), otherwise it will return an error. */ if (! mounted) return; setState(() { _ipAddress = result; }); } @override Widget build(BuildContext context) {var spacer = new SizedBox(height: 32.0); return new Scaffold( body: new Center( child: new Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ new RaisedButton( onPressed: _getIPAddress, child: New Text (' access to the weather forecast),), the new Text (' $_ipAddress. '), spacer,],),),); }}Copy the code
/ / Set BuildContext to true if initState is instantiated before initState is executed. / / Set BuildContext to true if initState is instantiated before initState is executed Mounted =false if dispose is executed, the state instance is dead and an error is reported when the code goes to setState().
Step 3 After the phone is connected to the computer, remember to turn on WIFI or mobile network.
Enable the VScode Debug tool to Debug the code, as shown in the figure below:
I believe that there should be no difficulty in understanding the above picture, please enjoy playing, APP test effect:
When WIFI is turned off, the response to failed requests is very fast. There is no browser error page that pops up after clicking. Flutter can detect whether WIFI or mobile networks are enabled from the hardware layer.
As you can see from the Dart2 syntax, the HTTP request code is very simple. It is much easier to use than the ES5 callback function. It also supports promise.
HttpClient client = new HttpClient();
client.getUrl(Uri.parse("http://www.example.com/"))
.then((HttpClientRequest request) {
// Optionally set up headers...
// Optionally write to the request object...
// Then call close.
...
return request.close();
})
.then((HttpClientResponse response) {
// Process the response.
...
});
Copy the code
This article is easy, students can go to the official website quoted in the article to practice English, ha ha ha, thank you for your support!