开发案例:Flutter开发天气预报小程序
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: WeatherForecast(),
);
}
}
class WeatherForecast extends StatefulWidget {
@override
_WeatherForecastState createState() => _WeatherForecastState();
}
class _WeatherForecastState extends State<WeatherForecast> {
String apiKey = "您的API密钥";
String city = "北京";
var weatherData;
var temp;
@override
void initState() {
super.initState();
getWeather();
}
getWeather() async {
var url = 'http://api.openweathermap.org/data/2.5/weather?q=$city&appid=$apiKey';
var response = await http.get(url);
setState(() {
weatherData = jsonDecode(response.body);
temp = weatherData['main']['temp'];
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('天气预报'),
),
body: Center(
child: temp == null
? CircularProgressIndicator()
: Text(
'${(temp - 273.15).toStringAsFixed(1)}°C',
style: Theme.of(context).textTheme.headline,
),
),
);
}
}
这段代码使用Flutter开发了一个简单的天气预报小程序。它从OpenWeatherMap的API获取天气数据,解析JSON响应,并在屏幕上显示当前城市的温度。代码简洁,注重教学,适合作为学习Flutter的入门案例。
评论已关闭