How to Implement API Calls in Flutter?

2019-03-11 23:24发布

问题:

I want to create a weather widget app by flutter but i am finding it difficult to do so as there is limited content on flutter. So if anyone knows how to Call , share your knowledge.

回答1:

If you're building a weather widget you'll almost certainly want a location plugin, which doesn't exist yet but is coming soon.

Here is some code that shows current temperature in San Francisco.

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.');
            }
          }
        )
      ),
    );
  }
}


回答2:

It could help someone, click here for official doc

1. Making Http Requests; import 'dart:io';
var httpClient = new HttpClient();
  • Create the client.

  • Construct the Uri.

  • Invoke the operation, and await the request object. Optionally,

  • configure the headers and body of the request.

  • Close the request, and await the response.

  • Decode the response

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