如何在 Flutter 中实现 API 次调用?

How to Implement API Calls in Flutter?

我想通过 flutter 创建一个天气小部件应用程序,但我发现很难这样做,因为 flutter 上的内容有限。因此,如果有人知道如何调用,请分享您的知识。

如果您正在构建天气小部件,您几乎肯定需要一个 location 插件,该插件目前尚不存在,但即将推出。

这是一些显示旧金山当前温度的代码。

import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(
    home: new MyHomePage(),
  ));
}

class Weather extends StatelessWidget {
  final Map<String, dynamic> data;
  Weather(this.data);
  Widget build(BuildContext context) {
    double temp = data['main']['temp'];
    return new Text(
      '${temp.toStringAsFixed(1)} °C',
      style: Theme.of(context).textTheme.display4,
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePageState createState() => new MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  Future<http.Response> _response;

  void initState() {
    super.initState();
    _refresh();
  }

  void _refresh() {
    setState(() {
      _response = http.get(
        'http://api.openweathermap.org/data/2.5/forecast'
          '?q=San+Francisco&units=metric&APPID=14cc828bff4e71286219858975c3e89a'
      );
    });
  }

  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Weather Example"),
      ),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.refresh),
        onPressed: _refresh,
      ),
      body: new Center(
        child: new FutureBuilder(
          future: _response,
          builder: (BuildContext context, AsyncSnapshot<http.Response> response) {
            if (!response.hasData)
              return new Text('Loading...');
            else if (response.data.statusCode != 200) {
              return new Text('Could not connect to weather service.');
            } else {
              Map<String, dynamic> json = JSON.decode(response.data.body);
              if (json['cod'] == 200)
                return new Weather(json);
              else
                return new Text('Weather service error: $json.');
            }
          }
        )
      ),
    );
  }
}

对大家有帮助,点击here获取官方文档

1. Making Http Requests; import 'dart:io';
var httpClient = new HttpClient();
  • 创建客户端。

  • 构建 Uri。

  • 调用操作,等待请求object。可选地,

  • 配置请求的headers和body。

  • 关闭请求,等待响应。

  • 解码响应

    get() async {
       var httpClient = new HttpClient();
       var uri = new Uri.http(
      'example.com', '/path1/path2', {'param1': '42', 'param2': 'foo'});
       var request = await httpClient.getUrl(uri);
       var response = await request.close();
       var responseBody = await response.transform(UTF8.decoder).join();
       Map data = JSON.decode(responseBody);
    }