Flutter天气查询插件flutter_qweather的使用

发布于 1周前 作者 ionicwang 来自 Flutter

Flutter天气查询插件flutter_qweather的使用

已有功能

  • 🚩 城市信息查询
  • 🚩 热门城市查询
  • 🚩 POI信息搜索
  • 🚩 POI范围搜索
  • 🚩 实时天气查询
  • 🚩 逐天天气查询
  • 🚩 逐时天气查询
  • 🚩 中国地区未来2小时内每5分钟降水查询
  • 🚩 当天生活指数查询
  • 🚩 三天生活指数查询
  • 🚩 天气灾害预警
  • 🚩 灾害预警列表
  • 🚩 空气质量实况
  • 🚩 空气质量5天预报
  • 🚩 历史天气
  • 🚩 历史空气质量
  • 🚩 日出日落
  • 🚩 月升月落月相
  • 🚩 太阳高度角
  • 🚩 潮汐
  • 🚩 潮流
  • 🚩 台风列表
  • 🚩 台风实况和路径
  • 🚩 台风预报

运行

注册账号并获取秘钥

首先你需要有一个和风天气的账号,点击这里进行注册。账号注册成功后,在应用管理中创建应用。注意包名不要写错。

本项目 example 的包名

Android:com.fluttercandies.flutter_qweather_example
iOS:com.fluttercandies.flutterQweatherExample
初始化插件
QweatherConfig config = QweatherConfig(
    publicIdForAndroid: 'HE210xxxxxxxxxxxxx',
    keyForAndroid: '8453863xxxxxxxxxxxxxxxxxxxxxxxxxx',
    publicIdForIos: 'HE210xxxxxxxxxxxxx',
    keyForIos: 'aead742xxxxxxxxxxxxxxxxxxxxxxxxx',
    biz: false,
    debug: true);
await FlutterQweather.instance.init(config);

location 为 LocationID 或者 经纬度。LocationID 可通过 geo 接口查询或查看 LocationList

实时天气查询

String location = '116.41,39.92';
WeatherNow? _resp = await FlutterQweather.instance.getWeatherNow(location);

逐天天气查询

String location = '116.41,39.92';
WeatherDailyResp? _resp = await FlutterQweather.instance.getWeatherDaily(location, WeatherDailyForecast.WeatherForecast3Day);

逐时天气查询

String location = '116.41,39.92';
WeatherHourlyResp? _resp = await FlutterQweather.instance.getWeatherHourly(location, WeatherHourlyForecast.WeatherForecast24Hour);

中国地区未来2小时内每5分钟降水查询

String location = '116.41,39.92';
WeatherMinutelyResp? _resp = await FlutterQweather.instance.getWeatherMinuteLy(location);

其他接口

相信你能看懂如何使用。

完整示例Demo

以下是一个完整的示例Demo,展示了如何使用 flutter_qweather 插件进行天气查询:

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_qweather/constants.dart';
import 'package:flutter_qweather/flutter_qweather.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';

  /// _location
  /// LocationID 或者 经纬度;
  /// LocationID 可通过geo 接口查询 或 查看 https://github.com/qwd/LocationList
  String _location = "106.227305,29.592024";
  TextEditingController _controller = TextEditingController();
  WeatherNowResp? _weatherNowResp;

  [@override](/user/override)
  void initState() {
    _controller.text = _location;
    super.initState();
    initPlatformState();
    initQweather();
  }

  // 初始化 Qweather
  Future<void> initQweather() async {
    QweatherConfig config = QweatherConfig(
        publicIdForAndroid: 'HE2104211812191773',
        keyForAndroid: '83716e1718b64b22b5b9615300ac366e',
        publicIdForIos: 'HE2104211812581604',
        keyForIos: 'e5d46c6726d34584ae16eb2e4520e610',
        biz: false,
        debug: true);
    await FlutterQweather.instance.init(config);
    // await FlutterQweather.instance.setDebug();
    await queryWeatherNow();
    FlutterQweather.instance.getAirNow(_location);
    // FlutterQweather.instance.geoPoiRangeLookup('116.40000,39.88999', PoiType.scenic);
    // FlutterQweather.instance.getWeatherMinuteLy(_location);
    // FlutterQweather.instance.geoPoiRangeLookup('116.40000,39.88999', PoiType.scenic);
    // FlutterQweather.instance.getIndices1Day('116.40000,39.88999', indicesTypes: {IndicesType.TRAV});
    // FlutterQweather.instance.getWarning('116.40000,39.88999');
    // FlutterQweather.instance.getWarningList(range: 'cn');
    // FlutterQweather.instance.getSun('116.40000,39.88999', '20220419');
    // FlutterQweather.instance.getMoon('116.40000,39.88999', '20220419');
    // FlutterQweather.instance.getSolarElevationAngle(
    //     location: '116.40000,39.88999', date: '20220419',
    //     time: "1230", tz: "0800",  alt: "430");
    // FlutterQweather.instance.getHistoricalWeather('116.40000,39.88999', '20220419');
    // FlutterQweather.instance.getHistoricalAir('116.40000,39.88999', '20220419');
  }

  // 查询实时天气
  Future<void> queryWeatherNow() async {
    setState(() => _weatherNowResp = null);
    // await Qweather.instance.getWeatherNow("101010100");
    _weatherNowResp = await FlutterQweather.instance.getWeatherNow(_location);
    setState(() {});
  }

  Future<void> initPlatformState() async {
    String platformVersion;
    try {
      platformVersion = await FlutterQweather.instance.platformVersion;
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }
    if (!mounted) return;
    setState(() => _platformVersion = platformVersion);
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('QWeather example app')),
        body: Column(
          children: [
            Padding(
              padding: EdgeInsets.all(20),
              child: IntrinsicHeight(
                child: Row(
                  children: [
                    Expanded(
                      child: TextField(
                        controller: _controller,
                        onChanged: (v) => _location = v,
                        decoration: InputDecoration(
                          hintText: "请输入LocationID 或者 经纬度",
                        ),
                      ),
                    ),
                    ElevatedButton(
                      child: Text("查询天气"),
                      onPressed: _weatherNowResp == null || _location.trim().isEmpty
                          ? null
                          : queryWeatherNow,
                    )
                  ],
                ),
              ),
            ),
            Expanded(
              child: _weatherNowResp == null
                  ? Center(child: Text("loading..."))
                  : _weatherNowWidget,
            ),
            Container(
              padding: EdgeInsets.all(64),
              child: Text('Running on: $_platformVersion\n'),
            )
          ],
        ),
      ),
    );
  }

  Widget get _weatherNowWidget {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20, vertical: 20),
      alignment: Alignment.center,
      child: ListView(
        children: [
          Text(
              "原始数据来源:             ${_weatherNowResp?.refer.sources.join(",")}"),
          Text(
              "使用许可:                ${_weatherNowResp?.refer.license.join(",")}"),
          Divider(),
          Text("接口更新时间:            ${_weatherNowResp?.basic.updateTime}"),
          Text("所查询城市的天气预报网页:   ${_weatherNowResp?.basic.fxLink}"),
          Divider(),
          Text("实况观测时间:            ${_weatherNowResp?.now.obsTime}"),
          Text("体感温度,默认单位:摄氏度: ${_weatherNowResp?.now.feelsLike}"),
          Text("温度,默认单位:摄氏度:    ${_weatherNowResp?.now.temp}"),
          Text("实况天气状况代码:         ${_weatherNowResp?.now.icon}"),
          Text("实况天气状况:             ${_weatherNowResp?.now.text}"),
          Text("风向360角度:             ${_weatherNowResp?.now.wind360}"),
          Text("风向:                   ${_weatherNowResp?.now.windDir}"),
          Text("风力:                   ${_weatherNowResp?.now.windScale}"),
          Text("风速,公里/小时:          ${_weatherNowResp?.now.windSpeed}"),
          Text("相对湿度:                ${_weatherNowResp?.now.humidity}"),
          Text("降水量:                  ${_weatherNowResp?.now.precip}"),
          Text("大气压强:                 ${_weatherNowResp?.now.pressure}"),
          Text("能见度,默认单位:公里:     ${_weatherNowResp?.now.vis}"),
          Text("云量:                    ${_weatherNowResp?.now.cloud}"),
          Text("实况云量:                 ${_weatherNowResp?.now.dew}"),
        ],
      ),
    );
  }
}

更多关于Flutter天气查询插件flutter_qweather的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter天气查询插件flutter_qweather的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用flutter_qweather插件来进行天气查询的示例代码。这个插件提供了访问和风天气(QWeather)API的功能,可以用来获取实时天气数据。

首先,确保你已经在pubspec.yaml文件中添加了flutter_qweather依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_qweather: ^最新版本号  # 请替换为最新的版本号

然后,运行flutter pub get来安装依赖。

接下来,你需要获取和风天气的API密钥。你可以在和风天气的开发者网站上注册并创建一个应用来获取这个密钥。

初始化插件并获取天气数据

  1. 初始化插件

在你的Flutter应用的主文件(通常是main.dart)中,初始化QWeather插件。

import 'package:flutter/material.dart';
import 'package:flutter_qweather/flutter_qweather.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化QWeather插件
  await QWeather.init(
    apiKey: '你的API密钥',  // 替换为你的和风天气API密钥
    location: Location(
      latitude: 39.9042,  // 默认位置(示例:北京)
      longitude: 116.4074,
    ),
    language: Language.zh_cn,  // 设置语言为中文
  );

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Weather App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: WeatherScreen(),
    );
  }
}
  1. 获取天气数据

创建一个新的屏幕或组件来显示天气数据。这里是一个简单的例子,展示了如何从和风天气API获取实时天气数据并显示。

import 'package:flutter/material.dart';
import 'package:flutter_qweather/flutter_qweather.dart';

class WeatherScreen extends StatefulWidget {
  @override
  _WeatherScreenState createState() => _WeatherScreenState();
}

class _WeatherScreenState extends State<WeatherScreen> {
  late WeatherModel? weatherData;

  @override
  void initState() {
    super.initState();
    _fetchWeatherData();
  }

  Future<void> _fetchWeatherData() async {
    try {
      // 获取实时天气数据
      final realTimeWeather = await QWeather.getRealTimeWeatherByLocation();
      setState(() {
        weatherData = realTimeWeather.data;
      });
    } catch (e) {
      print('Error fetching weather data: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Weather Information'),
      ),
      body: weatherData == null
          ? Center(child: CircularProgressIndicator())
          : Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('Location:', style: TextStyle(fontSize: 18)),
                  Text('${weatherData?.location?.name}'),
                  SizedBox(height: 16),
                  Text('Temperature:', style: TextStyle(fontSize: 18)),
                  Text('${weatherData?.now?.temp}°C'),
                  SizedBox(height: 16),
                  Text('Weather:', style: TextStyle(fontSize: 18)),
                  Text('${weatherData?.now?.text}'),
                  SizedBox(height: 16),
                  Text('Humidity:', style: TextStyle(fontSize: 18)),
                  Text('${weatherData?.now?.humidity}%'),
                ],
              ),
            ),
    );
  }
}

解释

  1. 初始化插件:在main.dart中,调用QWeather.init()方法来初始化插件,并传入API密钥和默认位置信息。

  2. 获取天气数据:在WeatherScreen组件中,使用QWeather.getRealTimeWeatherByLocation()方法获取实时天气数据。

  3. 显示天气数据:将获取到的天气数据存储在组件的状态中,并在UI中显示。

请确保你已经正确设置了和风天气的API密钥,并且API密钥具有访问实时天气数据的权限。如果你需要更多功能(如未来天气预测、空气质量等),可以参考flutter_qweather插件的官方文档,并根据需要扩展代码。

回到顶部