我想通过颤动创建一个天气小部件应用程序,但我发现很难这样做,因为颤动的内容有限。所以,如果有人知道如何打电话,分享你的知识。
如果你正在构建一个天气小部件,你几乎肯定会想要一个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();
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);
}
为了学习如何在颤动中进行非常简单的REST API调用,我建议使用checking out this tutorial
这是进行API调用并在列表视图中填充数据的基本演示。