Flutter天气预报插件adv_flutter_weather的使用
Flutter天气预报插件 adv_flutter_weather
的使用
adv_flutter_weather
是一个丰富且酷炫的天气动态背景插件,支持15种天气类型。它是基于 flutter_weather_bg
和 flutter_weather_bg_null_safety
进行了更新和改进。
特性
- 支持15种天气类型:晴天、傍晚晴天、多云、傍晚多云、阴天、小到中雨、大雪、雾霾、浮尘、雷暴等。
- 支持动态缩放大小,适应多种场景显示。
- 支持在切换天气类型时的动画效果。
支持的平台
- Flutter Android
- Flutter iOS
- Flutter Web
- Flutter 桌面端
安装
在您的 pubspec.yaml
文件中添加以下依赖:
dependencies:
adv_flutter_weather: ^1.0.0
然后导入该包:
import 'package:adv_flutter_weather/flutter_weather_bg.dart';
如何使用
要配置天气类型,可以通过创建 WeatherBg
来实现,您需要传入宽度和高度来完成最终的显示效果。
示例代码
以下是一个完整的示例 Demo,展示了如何使用 adv_flutter_weather
插件。
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:adv_flutter_weather/bg/weather_bg.dart';
import 'package:adv_flutter_weather/utils/print_utils.dart';
import 'package:adv_flutter_weather/utils/weather_type.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
[@override](/user/override)
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
[@override](/user/override)
void initState() {
super.initState();
}
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: const HomePage(),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
Widget _buildItem(BuildContext context, String desc, WeatherType weatherType) {
double width = MediaQuery.of(context).size.width;
double marginLeft = 10.0;
double marginTop = 8.0;
double itemWidth = (width - marginLeft * 4) / 2;
double itemHeight = itemWidth * 1.5;
var radius = 10.0;
return SizedBox(
width: itemWidth,
height: itemHeight,
child: Card(
elevation: 7,
margin: EdgeInsets.symmetric(horizontal: marginLeft, vertical: marginTop),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(radius)),
child: ClipPath(
clipper: ShapeBorderClipper(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(radius))),
child: Stack(
children: [
WeatherBg(
weatherType: weatherType,
width: itemWidth,
height: itemHeight,
),
BackdropFilter(
filter: ImageFilter.blur(sigmaX: 2.5, sigmaY: 2.5),
child: InkWell(
child: Center(
child: Text(
desc,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 20),
),
),
onTap: () {
// 可以在这里添加点击事件处理逻辑
},
),
),
],
),
),
),
);
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Wrap(
children: [
_buildItem(context, "Sunny", WeatherType.sunny),
_buildItem(context, "Cloudy", WeatherType.cloudy),
_buildItem(context, "Heavy Rain", WeatherType.heavyRainy),
_buildItem(context, "Snow", WeatherType.lightSnow),
],
),
),
);
}
}
更多关于Flutter天气预报插件adv_flutter_weather的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter天气预报插件adv_flutter_weather的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是一个使用 adv_flutter_weather
插件的示例代码案例。这个插件可以帮助你快速集成天气预报功能到你的 Flutter 应用中。以下示例展示了如何设置插件、获取当前天气数据,并显示基本的天气信息。
1. 添加依赖
首先,你需要在 pubspec.yaml
文件中添加 adv_flutter_weather
插件的依赖:
dependencies:
flutter:
sdk: flutter
adv_flutter_weather: ^最新版本号 # 请替换为最新版本号
然后运行 flutter pub get
以获取依赖。
2. 配置插件
在你的 Flutter 项目中,创建一个新的 Dart 文件(例如 weather_service.dart
)来配置和使用 adv_flutter_weather
插件。
// weather_service.dart
import 'package:flutter/material.dart';
import 'package:adv_flutter_weather/adv_flutter_weather.dart';
class WeatherService {
late WeatherClient weatherClient;
WeatherService() {
// 初始化 WeatherClient,这里需要你的API Key,可以从相关天气服务获取
weatherClient = WeatherClient(
apiKey: 'YOUR_API_KEY_HERE', // 请替换为你的API Key
language: 'zh_cn' // 设置语言为中文
);
}
Future<WeatherResponse?> getCurrentWeather(String location) async {
try {
// 获取当前天气
final response = await weatherClient.getCurrentWeatherByLocation(location);
return response;
} catch (e) {
print('Error fetching weather: $e');
return null;
}
}
}
3. 使用插件获取并显示天气数据
在你的主页面(例如 main.dart
)中使用 WeatherService
来获取并显示天气数据。
// main.dart
import 'package:flutter/material.dart';
import 'weather_service.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Weather App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: WeatherScreen(),
);
}
}
class WeatherScreen extends StatefulWidget {
@override
_WeatherScreenState createState() => _WeatherScreenState();
}
class _WeatherScreenState extends State<WeatherScreen> {
late WeatherService weatherService;
WeatherResponse? weatherResponse;
@override
void initState() {
super.initState();
weatherService = WeatherService();
fetchWeather('Beijing'); // 替换为你想要查询的城市
}
void fetchWeather(String location) async {
weatherResponse = await weatherService.getCurrentWeather(location);
if (mounted) {
setState(() {});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Weather App'),
),
body: weatherResponse == null
? Center(child: CircularProgressIndicator())
: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'城市: ${weatherResponse?.location?.name ?? ''}',
style: TextStyle(fontSize: 24),
),
SizedBox(height: 16),
Text(
'温度: ${weatherResponse?.current?.temp_c ?? ''}°C',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
Text(
'天气: ${weatherResponse?.current?.weather[0]?.description ?? ''}',
style: TextStyle(fontSize: 18),
),
SizedBox(height: 16),
Text(
'湿度: ${weatherResponse?.current?.humidity ?? ''}%',
style: TextStyle(fontSize: 16),
),
Text(
'风速: ${weatherResponse?.current?.wind_speed ?? ''} m/s',
style: TextStyle(fontSize: 16),
),
],
),
),
);
}
}
注意事项
- API Key:确保你已经从相关天气服务(如 OpenWeatherMap、Weatherstack 等)获取了有效的 API Key,并将其替换到
WeatherClient
的初始化中。 - 错误处理:在实际应用中,你应该添加更多的错误处理逻辑,以确保网络错误或数据解析错误能够被妥善处理。
- UI优化:这个示例代码仅展示了基本的天气信息显示,你可以根据需求进一步优化 UI,例如添加图标、动画效果等。
希望这个示例代码对你有所帮助!