如何在Flutter中实现API调用? [英] How to Implement API Calls in Flutter?

查看:826
本文介绍了如何在Flutter中实现API调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

如果要构建天气小部件,几乎可以肯定需要

  import'dart:async'; 
导入 dart:convert;
导入 package:http / http.dart为http;
导入的 package:flutter / material.dart;

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

类Weather扩展了StatelessWidget {
final Map< String,dynamic>数据;
天气(this.data);
Widget build(BuildContext context){
double temp = data [’main’] [’temp’];
返回新文本(
’$ {temp.toStringAsFixed(1)}°C,
样式:Theme.of(context).textTheme.display4,
);
}
}

类MyHomePage扩展了StatefulWidget {
MyHomePageState createState()=>新的MyHomePageState();
}

类MyHomePageState扩展了State< MyHomePage> {
Future< http.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 = 14cc828bff4e712862198519855c3e89a'
);
});
}

窗口小部件build(BuildContext context){
return new Scaffold(
appBar:new AppBar(
title:new Text( Weather Example ),
),
floatActionButton: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 )
返回新文本('无法连接到气象服务。');
返回新文本('正在加载...');
否则,如果(response.data.statusCode!= 200){
返回新文本('无法连接到气象服务。 ');
}否则{
Map< String,dynamic> json = JSON.decode(response.data.body);
if(json ['cod'] == 200)
返回新的Weather(json);
否则
返回新文本(天气服务错误:$ json。);
}
}

),
);
}
}


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.

解决方案

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

这篇关于如何在Flutter中实现API调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆