鸿蒙版天气预报应用引入Flutter三方库table_calendar实现个性化天气日历

C++STL—pair<int,int>与unordered_map的结合使用 因为unordered_map内部是由哈希表实现的,哈希表中的每一项为一个桶,分别装着键和值,原stl中不包含pair<int,int>类型的键,所以需要自定义 #include <bits/stdc++.h> using namespace std; // 分别计算出内置类型的 Hash Value 然后对它们进行 Combine 得到一个哈希值 // 一般直接采用移位加异或(XOR)得到哈希值 struct HashFunc { template<typename T, 阅读详情

📚 目录

1. 概述

1.1 什么是 Table Calendar?

table_calendar 是一个功能强大的 Flutter 日历组件库,提供了:

  • ✅ 美观的日历界面(Material Design 风格)
  • ✅ 日期选择功能
  • ✅ 自定义标记和样式
  • ✅ 多格式支持(月视图、周视图、2周视图)
  • ✅ 事件标记和自定义构建器

1.2 在本项目中的应用

我们使用 table_calendar 实现一个个性化天气日历,功能包括:

  • 📅 查看历史天气:显示近30天的历史天气数据
  • 🔮 查看未来预报:显示未来15天的天气预报
  • 🎯 智能标注:自动标注降水💧、高温🔥、预警🚨等特殊天气
  • 🔍 详情查看:点击日期查看详细天气信息
  • 🌍 多城市支持:自动读取当前城市,支持切换城市

image-20260129163724591

1.3 功能流程图

📱 用户打开天气日历

📍 加载当前城市

📡 加载天气数据

🔮 获取未来15天预报

📜 获取历史30天数据

⚠️ 获取天气预警

💾 存储到缓存

🏷️ 生成日历标注

📅 显示日历和标记

👆 用户选择日期

📊 显示天气详情

显示温度/天气/标注/预警


2. 引入三方库

2.1 添加依赖

在 pubspec.yaml 文件的 dependencies 部分添加:

dependencies:
  flutter:
    sdk: flutter
  
  # 日历组件
  table_calendar: ^3.1.2
  
  # # 用于存储城市信息,需要引入鸿蒙化的依赖
  shared_preferences: 
    git:
      url: "https://gitcode.com/openharmony-tpc/flutter_packages.git"
      path: "packages/shared_preferences/shared_preferences"

2.2 安装依赖

在项目根目录运行:

flutter pub get

2.3 依赖说明

依赖包版本用途
table_calendar^3.1.2日历组件核心库,提供日历UI和交互功能
shared_preferences^2.2.2用于读取当前城市信息

3. 目录结构

3.1 项目结构

lib/
├── screens/
│   └── weather_calendar_page.dart    # 天气日历页面(主要文件)
├── models/
│   ├── weather_models.dart           # 天气数据模型
│   └── weather_alert_model.dart      # 预警数据模型
├── services/
│   ├── weather_service.dart          # 天气服务(API调用)
│   └── weather_alert_service.dart    # 预警服务
└── main.dart                         # 应用入口

3.2 文件说明

  • weather_calendar_page.dart:天气日历页面的主要实现文件

    • 包含日历组件
    • 天气数据加载和显示
    • 日历标注功能
    • 预警详情显示
  • weather_models.dart:天气数据模型

    • Daily:每日天气预报数据
    • DailyForecastResponse:天气预报响应
  • weather_alert_model.dart:预警数据模型

    • WeatherAlert:天气预警数据
    • MarkerType:标注类型枚举
    • CalendarMarker:日历标注数据
  • weather_service.dart:天气服务

    • getDailyForecast():获取天气预报
    • 支持 3d、7d、10d、15d、30d 预报
  • weather_alert_service.dart:预警服务

    • getWeatherAlerts():获取天气预警列表

4. 从零开始实现

4.1 步骤1:创建页面文件

创建 lib/screens/weather_calendar_page.dart 文件,先搭建基础结构:

import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../api/weather_service.dart';
import '../models/weather_models.dart';
import '../models/weather_alert_model.dart';
import '../services/weather_alert_service.dart';

/// 天气日历页面
class WeatherCalendarPage extends StatefulWidget {
  const WeatherCalendarPage({super.key});

  
  State<WeatherCalendarPage> createState() => _WeatherCalendarPageState();
}

class _WeatherCalendarPageState extends State<WeatherCalendarPage> {
  // 服务实例
  final WeatherService _weatherService = WeatherService();
  final WeatherAlertService _alertService = WeatherAlertService();
  
  // 日历状态
  late ValueNotifier<List<DateTime>> _selectedDays;
  DateTime _focusedDay = DateTime.now();
  DateTime _selectedDay = DateTime.now();
  CalendarFormat _calendarFormat = CalendarFormat.month;
  
  // 当前城市
  String _currentCityId = '101010100';
  String _currentCityName = '北京';
  
  // 数据缓存
  final Map<String, DailyForecastResponse> _forecastCache = {};
  final Map<String, Map<String, dynamic>> _historicalCache = {};
  final Map<String, List<WeatherAlert>> _alertCache = {};
  
  // 标注数据
  final Map<DateTime, List<CalendarMarker>> _markers = {};
  
  // 加载状态
  bool _isLoading = false;

  
  void initState() {
    super.initState();
    _selectedDays = ValueNotifier([]);
    _weatherService.init();
    _loadCurrentCity();
    _loadWeatherData();
  }

  
  void dispose() {
    _selectedDays.dispose();
    super.dispose();
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('📅 天气日历 - $_currentCityName'),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _loadWeatherData,
            tooltip: '刷新天气数据',
          ),
        ],
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : RefreshIndicator(
              onRefresh: _loadWeatherData,
              child: Column(
                children: [
                  _buildCalendar(),
                  const Divider(),
                  Expanded(child: _buildWeatherDetail()),
                ],
              ),
            ),
    );
  }

  // 后续步骤会逐步实现这些方法
  Widget _buildCalendar() {
    return const SizedBox.shrink();
  }

  Widget _buildWeatherDetail() {
    return const SizedBox.shrink();
  }
}

💡 新手提示:

  • StatefulWidget 用于需要状态管理的页面
  • initState() 在页面创建时调用,适合初始化数据
  • dispose() 在页面销毁时调用,用于释放资源

4.2 步骤2:实现城市加载

添加加载当前城市的方法:

/// 加载当前城市
Future<void> _loadCurrentCity() async {
  try {
    final prefs = await SharedPreferences.getInstance();
    final cityId = prefs.getString('current_location_id');
    final cityName = prefs.getString('current_city_name');
    
    if (cityId != null && cityName != null) {
      setState(() {
        _currentCityId = cityId;
        _currentCityName = cityName;
      });
    }
  } catch (e) {
    debugPrint('加载当前城市失败: $e');
  }
}

💡 新手提示:

  • SharedPreferences 用于存储简单的键值对数据
  • setState() 用于更新UI,必须调用才能看到变化
  • debugPrint() 用于调试输出,不会影响生产环境

image-20260129162857688

4.3 步骤3:实现数据加载

添加天气数据加载方法:

/// 加载天气数据(主方法)
Future<void> _loadWeatherData() async {
  setState(() {
    _isLoading = true;
  });
  
  try {
    // 并行加载三种数据
    await Future.wait([
      _loadForecast(),           // 未来15天预报
      _loadHistoricalWeather(),  // 历史30天数据
      _loadWeatherAlerts(),      // 天气预警
    ]);
    
    // 生成标注
    _generateMarkers();
  } catch (e) {
    debugPrint('加载天气数据失败: $e');
  } finally {
    setState(() {
      _isLoading = false;
    });
  }
}

/// 加载未来15天预报
Future<void> _loadForecast() async {
  try {
    final forecast = await _weatherService.getDailyForecast(
      _currentCityId,
      days: '15d',
    );
    
    setState(() {
      _forecastCache[_currentCityId] = forecast;
    });
  } catch (e) {
    debugPrint('加载预报失败: $e');
  }
}

/// 加载近30天历史天气
Future<void> _loadHistoricalWeather() async {
  try {
    // 注意:和风天气API可能需要付费版本才能获取历史天气
    // 这里使用模拟数据作为示例
    final now = DateTime.now();
    final historicalData = <String, Map<String, dynamic>>{};
    
    for (int i = 1; i <= 30; i++) {
      final date = now.subtract(Duration(days: i));
      final dateKey = _formatDate(date);
      
      // 模拟历史天气数据
      historicalData[dateKey] = {
        'tempMax': 20 + (i % 10),
        'tempMin': 10 + (i % 8),
        'textDay': ['晴', '多云', '阴', '小雨'][i % 4],
        'precip': i % 5 == 0 ? 5.0 + (i % 3) : 0.0,
      };
    }
    
    setState(() {
      _historicalCache[_currentCityId] = historicalData;
    });
  } catch (e) {
    debugPrint('加载历史天气失败: $e');
  }
}

/// 加载天气预警
Future<void> _loadWeatherAlerts() async {
  try {
    final alerts = await _alertService.getWeatherAlerts(_currentCityId);
    setState(() {
      _alertCache[_currentCityId] = alerts;
    });
    debugPrint('加载天气预警成功: ${alerts.length} 条');
  } catch (e) {
    debugPrint('加载天气预警失败: $e');
  }
}

/// 格式化日期为字符串(YYYY-MM-DD)
String _formatDate(DateTime date) {
  return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
}

💡 新手提示:

  • Future.wait() 可以并行执行多个异步操作,提高效率
  • 使用 try-catch 捕获错误,避免应用崩溃
  • finally 块确保无论成功失败都会执行(如关闭加载状态)

4.4 步骤4:实现日历组件

实现 _buildCalendar() 方法:

/// 构建日历组件
Widget _buildCalendar() {
  return TableCalendar(
    // 设置日历显示范围(前后各一年)
    firstDay: DateTime.now().subtract(const Duration(days: 365)),
    lastDay: DateTime.now().add(const Duration(days: 365)),
    
    // 当前聚焦的日期
    focusedDay: _focusedDay,
    
    // 判断日期是否被选中
    selectedDayPredicate: (day) => isSameDay(_selectedDay, day),
    
    // 日历格式(月/周/2周)
    calendarFormat: _calendarFormat,
    
    // 格式切换回调
    onFormatChanged: (format) {
      setState(() {
        _calendarFormat = format;
      });
    },
    
    // 日期选择回调
    onDaySelected: (selectedDay, focusedDay) {
      setState(() {
        _selectedDay = selectedDay;
        _focusedDay = focusedDay;
      });
    },
    
    // 页面切换回调
    onPageChanged: (focusedDay) {
      setState(() {
        _focusedDay = focusedDay;
      });
    },
    
    // 自定义标记构建器
    calendarBuilders: CalendarBuilders(
      markerBuilder: (context, date, events) {
        final markers = _markers[date];
        if (markers == null || markers.isEmpty) {
          return null; // 没有标记时返回 null
        }
        
        // 显示标记(小圆点)
        return Positioned(
          bottom: 1,
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: markers.map((marker) {
              // 根据标记类型选择颜色
              Color markerColor;
              switch (marker.type) {
                case MarkerType.precipitation:
                  markerColor = Colors.blue;  // 蓝色:降水
                  break;
                case MarkerType.highTemperature:
                  markerColor = Colors.red;   // 红色:高温
                  break;
                case MarkerType.alert:
                  markerColor = Colors.orange; // 橙色:预警
                  break;
              }
              
              return Container(
                margin: const EdgeInsets.symmetric(horizontal: 1),
                width: 6,
                height: 6,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: markerColor,
                ),
              );
            }).toList(),
          ),
        );
      },
    ),
    
    // 日历样式
    calendarStyle: CalendarStyle(
      todayDecoration: BoxDecoration(
        color: Colors.blue.shade100,
        shape: BoxShape.circle,
      ),
      selectedDecoration: BoxDecoration(
        color: Colors.blue,
        shape: BoxShape.circle,
      ),
      markerDecoration: const BoxDecoration(
        color: Colors.transparent,
      ),
    ),
    
    // 头部样式
    headerStyle: HeaderStyle(
      formatButtonVisible: true,  // 显示格式切换按钮
      titleCentered: true,         // 标题居中
      formatButtonShowsNext: false,
      formatButtonDecoration: BoxDecoration(
        color: Colors.blue.shade100,
        borderRadius: BorderRadius.circular(8),
      ),
      formatButtonTextStyle: const TextStyle(
        color: Colors.blue,
        fontWeight: FontWeight.bold,
      ),
    ),
  );
}

💡 新手提示:

  • isSameDay() 是 table_calendar 提供的工具函数,用于比较两个日期是否为同一天
  • Positioned 用于在日历单元格中定位标记
  • markerBuilder 返回 null 表示该日期没有标记

image-20260129162835896

4.5 步骤5:实现标注生成

添加 _generateMarkers() 方法:

/// 生成日历标注
void _generateMarkers() {
  _markers.clear(); // 清空现有标注
  
  // 1. 处理预报数据
  final forecast = _forecastCache[_currentCityId];
  if (forecast?.daily != null) {
    for (final day in forecast!.daily!) {
      if (day.fxDate == null) continue;
      
      try {
        final date = DateTime.parse(day.fxDate!);
        final markers = <CalendarMarker>[];
        
        // 检查降水
        if (day.precip != null && day.precip!.isNotEmpty) {
          final precipValue = double.tryParse(day.precip!);
          if (precipValue != null && precipValue > 0) {
            markers.add(CalendarMarker(
              type: MarkerType.precipitation,
              date: date,
            ));
          }
        }
        
        // 检查高温(温度 > 35度)
        if (day.tempMax != null && day.tempMax!.isNotEmpty) {
          final tempMaxValue = int.tryParse(day.tempMax!);
          if (tempMaxValue != null && tempMaxValue > 35) {
            markers.add(CalendarMarker(
              type: MarkerType.highTemperature,
              date: date,
            ));
          }
        }
        
        if (markers.isNotEmpty) {
          _markers[date] = markers;
        }
      } catch (e) {
        debugPrint('解析日期失败: ${day.fxDate}, error: $e');
      }
    }
  }
  
  // 2. 处理历史数据(逻辑类似)
  final historical = _historicalCache[_currentCityId];
  if (historical != null) {
    historical.forEach((dateKey, data) {
      try {
        final date = DateTime.parse(dateKey);
        final markers = <CalendarMarker>[];
        
        if (data['precip'] != null && data['precip'] > 0) {
          markers.add(CalendarMarker(
            type: MarkerType.precipitation,
            date: date,
          ));
        }
        
        if (data['tempMax'] != null && data['tempMax'] > 35) {
          markers.add(CalendarMarker(
            type: MarkerType.highTemperature,
            date: date,
          ));
        }
        
        if (markers.isNotEmpty) {
          _markers[date] = markers;
        }
      } catch (e) {
        debugPrint('解析历史日期失败: $dateKey, error: $e');
      }
    });
  }
  
  // 3. 处理预警数据
  final alerts = _alertCache[_currentCityId] ?? [];
  for (final alert in alerts) {
    // 预警可能跨多天,需要标记预警期间的所有日期
    final startDate = DateTime(
      alert.startTime.year,
      alert.startTime.month,
      alert.startTime.day,
    );
    final endDate = DateTime(
      alert.endTime.year,
      alert.endTime.month,
      alert.endTime.day,
    );
    
    var currentDate = startDate;
    while (!currentDate.isAfter(endDate)) {
      if (!_markers.containsKey(currentDate)) {
        _markers[currentDate] = [];
      }
      
      // 检查是否已有预警标记
      final hasAlert = _markers[currentDate]!.any(
        (m) => m.type == MarkerType.alert,
      );
      
      if (!hasAlert) {
        _markers[currentDate]!.add(CalendarMarker(
          type: MarkerType.alert,
          date: currentDate,
          alert: alert, // 保存预警信息
        ));
      }
      
      currentDate = currentDate.add(const Duration(days: 1));
    }
  }
  
  setState(() {}); // 更新UI
}

💡 新手提示:

  • 标注生成逻辑分为三部分:预报数据、历史数据、预警数据
  • 预警可能跨多天,需要用循环标记所有日期
  • 最后调用 setState() 更新UI显示

image-20260129163143909

4.6 步骤6:实现天气详情显示

实现 _buildWeatherDetail() 方法:

/// 获取指定日期的天气数据
Map<String, dynamic>? _getWeatherForDate(DateTime date) {
  final dateKey = _formatDate(date);
  final now = DateTime.now();
  
  // 未来日期或今天:从预报中获取
  if (date.isAfter(now) || isSameDay(date, now)) {
    final forecast = _forecastCache[_currentCityId];
    if (forecast?.daily != null) {
      for (final day in forecast!.daily!) {
        if (day.fxDate == dateKey) {
          return {
            'tempMax': day.tempMax ?? '--',
            'tempMin': day.tempMin ?? '--',
            'textDay': day.textDay ?? '未知',
            'precip': day.precip ?? '0',
          };
        }
      }
    }
  } else {
    // 历史日期:从历史数据中获取
    final historical = _historicalCache[_currentCityId];
    if (historical != null && historical.containsKey(dateKey)) {
      return historical[dateKey];
    }
  }
  
  return null;
}

/// 构建天气详情
Widget _buildWeatherDetail() {
  final weatherData = _getWeatherForDate(_selectedDay);
  
  if (weatherData == null) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(Icons.info_outline, size: 48, color: Colors.grey),
          const SizedBox(height: 16),
          Text(
            '暂无 ${_formatDate(_selectedDay)} 的天气数据',
            style: TextStyle(color: Colors.grey.shade600),
          ),
        ],
      ),
    );
  }
  
  final markers = _markers[_selectedDay] ?? [];
  final isFuture = _selectedDay.isAfter(DateTime.now());
  
  return SingleChildScrollView(
    padding: const EdgeInsets.all(16),
    child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 日期标题
        Text(
          _formatDate(_selectedDay),
          style: const TextStyle(
            fontSize: 24,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 8),
        Text(
          isFuture ? '📅 预报' : '📜 历史',
          style: TextStyle(
            fontSize: 14,
            color: Colors.grey.shade600,
          ),
        ),
        const SizedBox(height: 24),
        
        // 天气卡片
        Card(
          elevation: 2,
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 天气状况
                Row(
                  children: [
                    Text(
                      weatherData['textDay'] ?? '未知',
                      style: const TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(width: 16),
                    _getWeatherIcon(weatherData['textDay'] ?? ''),
                  ],
                ),
                const SizedBox(height: 16),
                
                // 温度
                Row(
                  children: [
                    Text(
                      '${weatherData['tempMax'] ?? '--'}°',
                      style: const TextStyle(
                        fontSize: 32,
                        fontWeight: FontWeight.bold,
                        color: Colors.orange,
                      ),
                    ),
                    const SizedBox(width: 8),
                    Text(
                      '/ ${weatherData['tempMin'] ?? '--'}°',
                      style: TextStyle(
                        fontSize: 24,
                        color: Colors.grey.shade600,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 16),
                
                // 标注信息(Chip标签)
                if (markers.isNotEmpty) ...[
                  const Divider(),
                  const SizedBox(height: 8),
                  Wrap(
                    spacing: 8,
                    runSpacing: 8,
                    children: markers.map((marker) {
                      IconData icon;
                      String label;
                      Color color;
                      Color backgroundColor;
                      
                      switch (marker.type) {
                        case MarkerType.precipitation:
                          icon = Icons.water_drop;
                          label = '🌧️ 有降水';
                          color = Colors.blue;
                          backgroundColor = Colors.blue.shade50;
                          break;
                        case MarkerType.highTemperature:
                          icon = Icons.wb_sunny;
                          label = '🌡️ 高温';
                          color = Colors.red;
                          backgroundColor = Colors.red.shade50;
                          break;
                        case MarkerType.alert:
                          icon = Icons.warning;
                          label = '⚠️ 天气预警';
                          color = Colors.orange;
                          backgroundColor = Colors.orange.shade50;
                          break;
                      }
                      
                      return Chip(
                        avatar: Icon(icon, size: 18, color: color),
                        label: Text(label, style: const TextStyle(fontSize: 12)),
                        backgroundColor: backgroundColor,
                      );
                    }).toList(),
                  ),
                ],
                
                // 降水量
                if (weatherData['precip'] != null) ...[
                  Builder(
                    builder: (context) {
                      final precipValue = double.tryParse(weatherData['precip'].toString());
                      if (precipValue != null && precipValue > 0) {
                        return Column(
                          children: [
                            const SizedBox(height: 16),
                            Row(
                              children: [
                                const Icon(Icons.water_drop, color: Colors.blue),
                                const SizedBox(width: 8),
                                Text(
                                  '降水量: ${precipValue.toStringAsFixed(1)}mm',
                                  style: const TextStyle(fontSize: 14),
                                ),
                              ],
                            ),
                          ],
                        );
                      }
                      return const SizedBox.shrink();
                    },
                  ),
                ],
                
                // 预警信息(详细)
                if (markers.any((m) => m.type == MarkerType.alert)) ...[
                  Builder(
                    builder: (context) {
                      // 获取当天的预警
                      final alerts = _alertCache[_currentCityId] ?? [];
                      final dayAlerts = alerts.where((alert) {
                        final alertStart = DateTime(
                          alert.startTime.year,
                          alert.startTime.month,
                          alert.startTime.day,
                        );
                        final alertEnd = DateTime(
                          alert.endTime.year,
                          alert.endTime.month,
                          alert.endTime.day,
                        );
                        final selected = DateTime(
                          _selectedDay.year,
                          _selectedDay.month,
                          _selectedDay.day,
                        );
                        return !selected.isBefore(alertStart) && 
                               !selected.isAfter(alertEnd);
                      }).toList();
                      
                      if (dayAlerts.isEmpty) {
                        return const SizedBox.shrink();
                      }
                      
                      return Column(
                        children: [
                          const SizedBox(height: 16),
                          const Divider(),
                          const SizedBox(height: 8),
                          const Text(
                            '⚠️ 天气预警',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                              color: Colors.orange,
                            ),
                          ),
                          const SizedBox(height: 8),
                          ...dayAlerts.map((alert) {
                            return Container(
                              margin: const EdgeInsets.only(bottom: 8),
                              padding: const EdgeInsets.all(12),
                              decoration: BoxDecoration(
                                color: alert.isUrgent
                                    ? Colors.red.shade50
                                    : Colors.orange.shade50,
                                borderRadius: BorderRadius.circular(8),
                                border: Border.all(
                                  color: alert.isUrgent
                                      ? Colors.red.shade300
                                      : Colors.orange.shade300,
                                  width: 1,
                                ),
                              ),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Row(
                                    children: [
                                      Text(alert.icon, style: const TextStyle(fontSize: 20)),
                                      const SizedBox(width: 8),
                                      Expanded(
                                        child: Text(
                                          alert.title,
                                          style: const TextStyle(
                                            fontSize: 14,
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                      ),
                                      Container(
                                        padding: const EdgeInsets.symmetric(
                                          horizontal: 8,
                                          vertical: 4,
                                        ),
                                        decoration: BoxDecoration(
                                          color: alert.isUrgent ? Colors.red : Colors.orange,
                                          borderRadius: BorderRadius.circular(4),
                                        ),
                                        child: Text(
                                          alert.levelColor,
                                          style: const TextStyle(
                                            color: Colors.white,
                                            fontSize: 12,
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                  const SizedBox(height: 8),
                                  Text(alert.content, style: const TextStyle(fontSize: 12)),
                                  const SizedBox(height: 4),
                                  Text(
                                    '${_formatDate(alert.startTime)} 至 ${_formatDate(alert.endTime)}',
                                    style: TextStyle(
                                      fontSize: 11,
                                      color: Colors.grey.shade600,
                                    ),
                                  ),
                                ],
                              ),
                            );
                          }).toList(),
                        ],
                      );
                    },
                  ),
                ],
              ],
            ),
          ),
        ),
      ],
    ),
  );
}

/// 获取天气图标(Emoji)
Widget _getWeatherIcon(String text) {
  final iconMap = {
    '晴': '☀️',
    '多云': '⛅',
    '阴': '☁️',
    '小雨': '🌦️',
    '中雨': '🌧️',
    '大雨': '⛈️',
    '雪': '❄️',
  };
  
  return Text(
    iconMap[text] ?? '🌤️',
    style: const TextStyle(fontSize: 32),
  );
}

💡 新手提示:

  • SingleChildScrollView 用于可滚动内容
  • Builder 用于在条件渲染中声明变量
  • ... 展开运算符用于将列表展开为多个子元素

image-20260129163448436

4.7 步骤7:添加城市切换监听

添加 didChangeDependencies() 方法监听城市变化:


void didChangeDependencies() {
  super.didChangeDependencies();
  // 当页面重新显示时,检查城市是否有变化
  _checkCityChange();
}

/// 检查城市变化
Future<void> _checkCityChange() async {
  try {
    final prefs = await SharedPreferences.getInstance();
    final cityId = prefs.getString('current_location_id');
    final cityName = prefs.getString('current_city_name');
    
    if (cityId != null && 
        cityName != null && 
        (cityId != _currentCityId || cityName != _currentCityName)) {
      // 城市发生变化,重新加载数据
      await _loadCurrentCity();
      await _loadWeatherData();
    }
  } catch (e) {
    debugPrint('检查城市变化失败: $e');
  }
}

💡 新手提示:

  • didChangeDependencies() 在依赖变化时调用,适合监听外部数据变化
  • 比较城市ID和名称,避免重复加载

4.8 步骤8:添加标注类型定义

在文件末尾添加标注类型定义:

/// 日历标注类型
enum MarkerType {
  precipitation,    // 降水 💧
  highTemperature, // 高温 🔥
  alert,           // 预警 🚨
}

/// 日历标注数据
class CalendarMarker {
  final MarkerType type;
  final DateTime date;
  final WeatherAlert? alert; // 预警信息(仅当type为alert时有效)
  
  CalendarMarker({
    required this.type,
    required this.date,
    this.alert,
  });
}

4.9 步骤9:集成到导航栏

在 lib/screens/main_navigation_page.dart 中:

import 'weather_calendar_page.dart';

// 在 _buildScreens() 中添加
List<Widget> _buildScreens() {
  return [
    const HomePage(),
    const CityManagePage(),
    const WeatherDetailPage(),
    const WeatherCalendarPage(), // 新增
    const ProfilePage(),
  ];
}

// 在 _navBarsItems() 中添加
PersistentBottomNavBarItem(
  icon: const Icon(Icons.calendar_today),
  title: "天气日历",
  activeColorPrimary: Colors.teal,
  inactiveColorPrimary: Colors.grey,
  iconSize: 26,
),

5. 核心代码详解

5.1 数据加载流程图

💾 缓存 ⚠️ 预警服务 🌐 天气服务 📱 页面 👤 用户 💾 缓存 ⚠️ 预警服务 🌐 天气服务 📱 页面 👤 用户 打开天气日历 initState() _loadCurrentCity() getDailyForecast(15d) 返回预报数据 存储到_forecastCache _loadHistoricalWeather() 存储到_historicalCache getWeatherAlerts() 返回预警数据 存储到_alertCache _generateMarkers() 更新_markers 显示日历和标注 选择日期 _getWeatherForDate() 查询缓存数据 返回天气数据 显示天气详情

5.2 标注生成逻辑

有

无

有

无

有

无

开始生成标注

清空现有标注

处理预报数据

检查降水

添加蓝色标记

检查高温

添加红色标记

跳过

处理历史数据

检查降水/高温

添加标记

跳过

处理预警数据

遍历预警列表

计算预警日期范围

标记所有日期

添加橙色标记

更新UI

5.3 关键代码说明

5.3.1 日历组件配置
TableCalendar(
  firstDay: DateTime.now().subtract(const Duration(days: 365)),
  lastDay: DateTime.now().add(const Duration(days: 365)),
  // ... 其他配置
)

说明:

  • firstDay 和 lastDay 定义了日历的可显示范围
  • 设置为前后各一年,足够查看历史天气和未来预报
5.3.2 标记颜色映射
switch (marker.type) {
  case MarkerType.precipitation:
    markerColor = Colors.blue;   // 💧 蓝色:降水
    break;
  case MarkerType.highTemperature:
    markerColor = Colors.red;    // 🔥 红色:高温
    break;
  case MarkerType.alert:
    markerColor = Colors.orange; // 🚨 橙色:预警
    break;
}

说明:

  • 使用不同颜色区分不同类型的标记
  • 颜色选择符合用户直觉(蓝色=水,红色=热,橙色=警告)
5.3.3 预警跨天处理
var currentDate = startDate;
while (!currentDate.isAfter(endDate)) {
  // 标记每一天
  _markers[currentDate]!.add(CalendarMarker(...));
  currentDate = currentDate.add(const Duration(days: 1));
}

说明:

  • 预警可能持续多天,需要标记预警期间的所有日期
  • 使用循环逐日标记

6. 常见错误与解决方案

6.1 错误:TableCalendar 显示异常

错误信息:

RenderFlex overflowed by XX pixels

问题分析:
日历组件高度超出容器范围,导致布局溢出。

解决方案:

// ✅ 正确:使用 Column + Expanded
Column(
  children: [
    _buildCalendar(),  // 日历组件
    const Divider(),
    Expanded(          // 使用 Expanded 包裹详情区域
      child: _buildWeatherDetail(),
    ),
  ],
)

// ❌ 错误:直接使用 Column
Column(
  children: [
    _buildCalendar(),
    _buildWeatherDetail(), // 会导致溢出
  ],
)

其他注意事项:

  • 确保 firstDay 和 lastDay 设置合理(不要跨度太大)
  • 检查日历的 headerStyle 和 calendarStyle 是否设置了过大的 padding

6.2 错误:日期选择无响应

可能原因:

  • onDaySelected 回调未正确设置
  • selectedDayPredicate 逻辑错误
  • 忘记调用 setState()

解决方案:

// ✅ 正确:完整的选择逻辑
onDaySelected: (selectedDay, focusedDay) {
  setState(() {  // 必须调用 setState
    _selectedDay = selectedDay;
    _focusedDay = focusedDay;
  });
},

selectedDayPredicate: (day) {
  return isSameDay(_selectedDay, day);  // 使用 isSameDay 比较
},

6.3 错误:标记不显示

可能原因:

  • markerBuilder 返回 null
  • 标记数据未正确生成
  • 忘记调用 setState()

解决方案:

// ✅ 正确:确保标记数据已生成并更新UI
void _generateMarkers() {
  _markers.clear();
  // ... 生成标记逻辑
  setState(() {}); // 重要:调用 setState 更新UI
}

// ✅ 正确:markerBuilder 返回 Widget
markerBuilder: (context, date, events) {
  final markers = _markers[date];
  if (markers == null || markers.isEmpty) {
    return null; // 没有标记时返回 null
  }
  
  return Positioned(
    bottom: 1,
    child: Row(
      children: markers.map((marker) => _buildMarker(marker)).toList(),
    ),
  );
},

6.4 错误:日期格式化失败

错误信息:

FormatException: Invalid date format

解决方案:

// ✅ 正确:使用安全的日期格式化
String _formatDate(DateTime date) {
  return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
}

// ✅ 正确:解析日期时添加错误处理
try {
  final date = DateTime.parse(day.fxDate!);
  // 使用日期
} catch (e) {
  debugPrint('解析日期失败: ${day.fxDate}, error: $e');
  continue; // 跳过这条数据
}

6.5 错误:Builder 中无法声明变量

错误信息:

Error: Expected an identifier, but got 'final'.

问题分析:
在条件渲染的 ... 展开运算符中直接声明 final 变量会报错。

解决方案:

// ✅ 正确:使用 Builder 包裹
if (weatherData['precip'] != null) ...[
  Builder(
    builder: (context) {
      final precipValue = double.tryParse(weatherData['precip'].toString());
      if (precipValue != null && precipValue > 0) {
        return Column(
          children: [
            // ... 显示降水量
          ],
        );
      }
      return const SizedBox.shrink();
    },
  ),
]

// ❌ 错误:直接在展开运算符中声明变量
if (weatherData['precip'] != null) ...[
  final precipValue = ...; // 会报错
]

7. 进阶功能

7.1 自定义日历样式

calendarStyle: CalendarStyle(
  todayDecoration: BoxDecoration(
    color: Colors.blue.shade100,
    shape: BoxShape.circle,
  ),
  selectedDecoration: BoxDecoration(
    color: Colors.blue,
    shape: BoxShape.circle,
  ),
  weekendDecoration: BoxDecoration(
    color: Colors.grey.shade100,
    shape: BoxShape.circle,
  ),
  outsideDecoration: const BoxDecoration(
    shape: BoxShape.circle,
  ),
  markerDecoration: const BoxDecoration(
    color: Colors.transparent,
  ),
),

7.2 优化性能

使用缓存避免重复请求:

// 检查缓存中是否已有数据
if (_forecastCache.containsKey(_currentCityId)) {
  // 使用缓存数据
  _generateMarkers();
} else {
  // 加载新数据
  await _loadForecast();
}

使用 Future.wait 并行加载:

await Future.wait([
  _loadForecast(),
  _loadHistoricalWeather(),
  _loadWeatherAlerts(),
]);

7.3 添加加载状态

bool _isLoading = false;

Future<void> _loadWeatherData() async {
  setState(() {
    _isLoading = true;
  });
  
  try {
    // 加载数据
  } finally {
    setState(() {
      _isLoading = false;
    });
  }
}

// 在 build 中显示加载状态
body: _isLoading
    ? const Center(child: CircularProgressIndicator())
    : RefreshIndicator(...),

8. 总结

8.1 实现的功能

本教程详细介绍了如何使用 table_calendar 实现天气日历功能,已完成的功能包括:

  1. ✅ 引入三方库:添加 table_calendar 依赖
  2. ✅ 创建页面:实现天气日历页面组件
  3. ✅ 数据加载:加载历史天气、未来预报、天气预警
  4. ✅ 日历标注:实现降水💧、高温🔥、预警🚨标注
  5. ✅ 日期选择:实现日期选择和天气详情显示
  6. ✅ 预警详情:显示预警的详细信息
  7. ✅ 集成导航:添加到底部导航栏
  8. ✅ 城市切换:自动监听城市变化并重新加载数据
  9. ✅ 错误处理:常见错误及解决方案

8.2 核心功能

  • 📅 日历显示:支持月/周/2周视图切换,美观的 Material Design 风格
  • 📊 数据展示:显示近30天历史天气和未来15天天气预报
  • 🎯 智能标注:自动标注降水💧、高温🔥、预警🚨等特殊天气
    • 降水标注:蓝色圆点,当降水量 > 0 时显示
    • 高温标注:红色圆点,当最高温度 > 35°C 时显示
    • 预警标注:橙色圆点,当有天气预警时显示
  • 🔍 详情查看:点击日期查看详细天气信息
    • 温度信息(最高/最低温度)
    • 天气状况(晴、多云、雨等)
    • 降水量(如有)
    • 预警详情(如有预警,显示预警标题、内容、等级、时间范围)
  • 🔄 数据刷新:支持下拉刷新和手动刷新天气数据
  • 🌍 多城市支持:自动读取当前城市,支持切换城市查看不同地区的天气日历

8.5 完整功能流程图

🌧️ 有降水

🌡️ 高温>35°C

⚠️ 有预警

未来

历史

📱 应用启动

打开天气日历

📍 读取当前城市

📡 加载天气数据

🔮 获取未来15天预报

📜 获取历史30天数据

⚠️ 获取天气预警数据

💾 存储到预报缓存

💾 存储到历史缓存

💾 存储到预警缓存

🏷️ 生成标注数据

检查天气类型

添加蓝色标记

添加红色标记

添加橙色标记

📅 更新日历显示

👆 用户选择日期

日期类型

从预报缓存获取

从历史缓存获取

📊 显示天气详情

显示温度/天气/标注/预警


9. 参考资料


10. 功能演示流程图

💾 数据缓存 🌐 天气服务 📅 日历组件 📱 应用 👤 用户 💾 数据缓存 🌐 天气服务 📅 日历组件 📱 应用 👤 用户 打开天气日历 初始化日历 请求未来15天预报 返回预报数据 缓存预报数据 请求历史30天数据 返回历史数据 缓存历史数据 请求天气预警 返回预警数据 缓存预警数据 生成标注 显示日历和标注 选择日期 触发日期选择事件 查询天气数据 返回天气数据 显示天气详情 下拉刷新 重新请求数据 返回最新数据 更新日历显示 刷新完成

🎉 祝你开发顺利! 🚀
欢迎加入开源鸿蒙跨平台社区

上汽CPMP开发流程与A、B、C、D样 也叫验收样件或设计样件,是根据A样试制结果优化后的样件,外观、功能达到设计要求,B样可以是手工样件或者模具件,B样件的全维度产品功能和尺寸参数已经固化下来,并需要和最终的量产产品保持一致。为批量样件或生产样件、展示样件,是在A/B的基础上完善结果,此时的产品状态已经完全定型,并能够满足客户和市场提出的各类需求。预试生产(Pre-Production)----------------------------------------------------------------------→D样。 阅读详情

相关推荐

实战解析:在.NET中实现Dify API流式请求与响应的完整方案

本文详细解析了在.NET应用中对接Dify API时实现流式请求与响应的完整方案。针对传统后端“接收完才返回”的痛点,文章提供了基于ASP.NET Core的实战代码,通过配置HttpCompletionOption.ResponseHeadersRead和手动Flush响应流,构建高效的中转管道,确保AI回复能够像ChatGPT一样实时逐字推送到前端,显著提升用户体验。

weixin_29267307的博客 301

旅行拼贴册开发手记 03|HarmonyOS 7.0 精准碰一碰:屏幕坐标与格子命中判定【鸿蒙心迹】

滚动后格子位置已经更新,而裁剪范围仍来自上一次测量,这样拼出来的快照不能用于命中。把屏幕触点交给格子,看似只是几个大小比较,真正需要维护的是这些数字的含义。若两格之间存在间隙,前一格的右边界可能仍在间隙里,没有格子接纳。移动窗口与滚动分开执行,每次保存原矩形、裁剪范围及有效矩形,检查坐标变化是否与界面位置相符。现在保持输入不变,继续使用那张海边 JPEG,把注意力放到一个更小的问题上:给定系统返回的触点,应用凭什么认为它属于某个格子?窗口移动、页面滚动可以改变格子的屏幕位置,却不应该改变它的业务身份。

2601_95619323的博客 377

超融合架构实战:如何用3节点搭建企业级分布式存储系统?

本文详细介绍了如何利用3节点搭建企业级分布式存储系统的超融合架构实战指南。从硬件选型、网络配置到存储策略调优,提供了全面的实操建议和性能优化技巧,帮助企业实现高效、弹性的IT基础设施。特别适合需要简化运维、提升存储性能的中型企业参考。

weixin_29200485的博客 335

HarmonyOS7基础属性全解-总览导读篇

本文系统梳理 HarmonyOS7 ArkUI 的通用属性体系,以 8 大模块、9 篇文章构建完整知识地图。从链式调用原理出发,详解组件标识、显隐控制、背景设置、浮层、Z序、隐私遮罩与反色适配等核心能力,手把手搭建可运行的实战工程“HarmonyAttrLab”,助力开发者高效掌握声明式 UI 的底层逻辑与进阶技巧。

沉淀所学,分享所思,让热爱与成长同行。商务记录AI实战经验,助力开发者快速成长。 热爱AI,希望做出有影响力的技术成果。 技术点亮生活,分享连接价值与机会。 专注AI落地实战,陪你走好技术每一步。 300

proteus仿真51单片机操作指南:串口通信仿真配置详解

深入讲解如何在proteus仿真51单片机中实现串口通信,涵盖虚拟串口设置、电路连接与调试技巧,帮助开发者高效完成通信仿真验证。

weixin_36197669的博客 580

IBM 3560M3 R5 坏盘更换记录

公司一台老旧 3650M3在日常巡查过程中发现硬盘报错

ddriv的博客 3960

赛道二收官,参赛交付沉淀为可复用的开源鸿蒙 PC 三方库

2026 开源鸿蒙大学生创新大赛设了三条赛道,赛道二(开源鸿蒙 PC 专项积分赛)交出来的东西最不像「参赛作品」。系统与技术创新赛道交方案,校园与创新应用赛道交能装进设备的应用,赛道二交的是一批 PR——把清单里的 PC 类开源三方库搬到开源鸿蒙 PC 环境,让它编译通过、功能完整、上游测试跑得起来。这些库不是摆在展台上的样品,而是应用开发者写工程时要直接引用的依赖:一个库能不能用,决定的是一片应用能不能落在这套系统上。这类交付不好拿去路演,却有个实在的好处:做没做完,几乎不靠主观判断。

白天写代码,晚上追AI大模型,偶尔搞点八卦 开源动态|技术干货|实习机会|生态活动 我负责分享,你负责变强 248

挂载(Mount)是什么意思

挂载 = 把一个存储设备或文件系统“接入”到现有的目录树,使其内容能够被访问。

天赐好车的博客 299

HarmonyOS7 拖拽事件实战:从 onPreDrag 八阶段到 onDrop 投放(附完整案例)

onPreDrag八阶段(API 12)→(API 8)→onDragMove→onDrop→onDragEnd(API 10);决定"能不能拖、拖起来长什么样";setResultgetResult决定"这次拖拽算不算数";DragEvent的实时坐标()与速度(,vp/s)支撑仪表类需求,注意onDragMove的高频特性;@State数组更新必须splice整体替换或整体重赋值,直接改元素属性不刷新;长按约 500ms 才进入就绪待拖拽,快速滑动不触发拖拽。

沉淀所学,分享所思,让热爱与成长同行。商务记录AI实战经验,助力开发者快速成长。 热爱AI,希望做出有影响力的技术成果。 技术点亮生活,分享连接价值与机会。 专注AI落地实战,陪你走好技术每一步。 127

双目相机标定理论与编程实现

双目相机标定是计算机视觉中的重要任务,通过确定双目相机的内参和外参,可以实现立体视觉的深度感知和三维重建。通过使用OpenCV库提供的函数,我们可以方便地进行双目相机的标定工作。双目相机标定是计算机视觉中的重要任务,用于确定双目相机的内参和外参,以实现立体视觉的深度感知和三维重建。通过上述代码,我们可以获得左右相机的内参矩阵、畸变系数、旋转矩阵和平移矩阵等参数,从而完成双目相机的标定过程。使用双目相机采集一系列左右相机的图像,确保标定板在不同位置和角度下都能被双目相机拍摄到。函数来检测标定板的角点。

ByteKnight的博客 328

docker命令_获取镜像,创建容器,启动容器,进入容器,退出容器,停止容器,删除容器,列出镜像,删除镜像

1.数据准备

C/C++、嵌入式开发、深度学习算法、模型部署与推理优化 1091

HarmonyOS7 组件通用事件(一):四大事件总览——组件的生死、身位与存在感

广告和信息流卡片要曝光埋点,产品问"这张卡用户到底看没看见",你把打点挪进onAppear交差——ForEach一渲染全部触发,数据全是假的;悬浮角标要跟着目标组件走,目标一挪角标就得动,你翻遍了组件属性,没找到"监听它位置变化"的那一个;分屏、折叠屏一展开,页面尺寸变了要重新排版,你不知道该在哪个回调里接住"尺寸变了"这个信号;组件销毁时要停定时器、取消网络请求,页面退出后日志还在刷,你怀疑自己漏写了清理逻辑,翻文档才发现事件挂在哪儿都有讲究。组件的状态变了,我从哪儿知道?onAppear。

沉淀所学,分享所思,让热爱与成长同行。商务记录AI实战经验,助力开发者快速成长。 热爱AI,希望做出有影响力的技术成果。 技术点亮生活,分享连接价值与机会。 专注AI落地实战,陪你走好技术每一步。 285

2025_NIPS_RAGRouter: Learning to Route Queries to Multiple Retrieval-Augmented Language Models

该研究聚焦检索增强生成(RAG)场景下的大语言模型(LLM)路由问题,提出了首个RAG感知的路由框架RAGRouter。核心解决现有路由方法依赖静态参数知识、忽略检索文档动态影响的缺陷,通过融合文档嵌入、RAG能力嵌入与对比学习,捕捉RAG引发的模型知识表征变化,为每个查询-文档对选择最优LLM。实验覆盖5个知识密集型任务、15个开源/闭源LLM,验证了RAGRouter在性能上超越最佳单LLM和非RAG感知路由方法,且通过阈值机制实现低延迟约束下的性能-效率平衡。

UnknownBody_2的博客 283

HarmonyOS7 悬停事件实战:onHover、hoverEffect 四态与设备适配(附完整案例)

onHover(API 8)回调用布尔值报告光标进出,比鼠标事件的 action 比对省事;(API 15)是可选字段,取值前??0兜底;Auto跟随系统、Scale放大、Highlight浮起加深、None关默认效果;完全自定义样式前先设None;悬停沿组件树从子到父冒泡,截断;悬停是光标专属交互:触摸不触发,手机模拟器上鼠标被翻译成触摸也不触发,用做降级提示。悬停与点击、拖拽在同一批组件上的叠加共存,可以看汇合篇《HarmonyOS7 通用事件实战博客》的融合案例"桌面小组件工坊"。

沉淀所学,分享所思,让热爱与成长同行。商务记录AI实战经验,助力开发者快速成长。 热爱AI,希望做出有影响力的技术成果。 技术点亮生活,分享连接价值与机会。 专注AI落地实战,陪你走好技术每一步。 124

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

vb 6.0并口开发操作实例

vb6并口开发,简体中文,试例内有inpout32.dll动态链接库

03-HarmonyOS7-通用属性实战-布局约束

本文详解HarmonyOS 7中ArkTS的两大布局约束属性:aspectRatio与displayPriority。通过视频封面、正方形头像及响应式消息列表案例,演示如何用aspectRatio固定宽高比(如16:9),实现自适应拉伸;利用displayPriority按优先级动态隐藏内容,实现空间不足时的降级显示。代码简洁高效,兼容API 12+,助力构建灵活、响应式的UI布局。

沉淀所学,分享所思,让热爱与成长同行。商务记录AI实战经验,助力开发者快速成长。 热爱AI,希望做出有影响力的技术成果。 技术点亮生活,分享连接价值与机会。 专注AI落地实战,陪你走好技术每一步。 352

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

HarmonyOS7基础属性全解(九):禁用反色 allowForceDark——反色大潮里,这块颜色自己说了算(收官篇)

深色模式早已是应用标配。适配它的"正路"是双份资源(),精细但工作量大;对有大量存量代码的应用,官方从 API 20 起提供了"捷径"——反色能力(Force Dark)反色能力是在深浅色切换时自动对颜色值进行反色或变换。一行 C-API 开启后,深色模式下所有硬编码颜色自动反转,全量适配近在眼前。它是一把大刷子。品牌色#FF6A00的品牌橙反转后变成诡异蓝色,VI 全毁;设计感卡片:暖色调卡片被反转成冷色调,设计稿白做;与深色资源混用的页面:同一页面一半走资源配置、一半走反色,两套逻辑打架。

沉淀所学,分享所思,让热爱与成长同行。商务记录AI实战经验,助力开发者快速成长。 热爱AI,希望做出有影响力的技术成果。 技术点亮生活,分享连接价值与机会。 专注AI落地实战,陪你走好技术每一步。 102

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

HarmonyOS 7 调起系统分享,关掉面板和复制交接短签有何区别

初版把状态字段直接叫visibility,又把子组件选项叫enabled,编译器报10505001。自定义组件已经用这两个名称表达组件属性,字段类型与内建方法冲突。最后改成panelState和,保留原控件的可用性写法。改名只是让页面通过类型检查,后来仍需要实际走关闭和复制的流程,确认事件更新能画出来。

程序猿追的博客 321

HarmonyOS 7 随机密码生成器怎样遵守选中的规则

源码与 README见。在密码生成器里,点完「复制」之后还能做一次实际检查。密芽提供一个系统「粘贴」按钮,人工触发后,程序把本机剪贴板的主文本与当前预览逐字符比较,只在页面上报告是否一致。这个动作把一次验收分成了三步:生成的内容先通过选定规则,复制时写入系统,最后由系统授权的一次粘贴读回。下面沿这三个动作反查代码,任何一步都可在模拟器上单独重做。HarmonyOS 7 电脑模拟器宽窗全屏。复制临时演示值后,从系统粘贴读回,页面显示与当前结果一致。

程序猿追的博客 1万+

HarmonyOS 7 月历翻页后,月底的便签该跟哪一天

源码与 README见。

程序猿追的博客 1万+

HarmonyOS 7 Health Service Kit 实战:打通手表健康数据授权

本文以智能穿戴应用“腕上活力”为例,基于 HarmonyOS 7 与 Health Service Kit,实现手表健康数据授权模块。围绕 Client ID 配置、服务初始化、授权申请、状态查询和撤销管理,结合完整 ArkTS 代码,讲解部分授权、用户取消、重复请求及异步状态处理,并通过实际运行截图、逻辑测试与调用日志说明验证方法和接入问题定位。

leon_teacher 4454

HarmonyOS7 事件分发控制(四):addLocalInputEventMonitor 全局输入哨兵——API 26 新能力

前两篇的关卡都挂在组件树上:玻璃卡管自己,Stack 管孩子。展厅里的自助机在轮播投影的几秒里不能让人乱点屏幕——难道给页面上几十个组件挨个?儿童模式想把触摸整个锁住,只留键盘——总不能在每个页面上都盖一层蒙层吧?想给整个应用做一次输入审计,记下每一次触摸、每一次按键——在哪个组件上挂回调能挂得全?不该等事件走到组件那一步,应该在它进入 UI 之前就拦下。。它在链路图的最上游站岗——事件还没进到任何组件,你先拿到决定权:返回CONTINUE放行,返回BLOCK就地丢弃。

沉淀所学,分享所思,让热爱与成长同行。商务记录AI实战经验,助力开发者快速成长。 热爱AI,希望做出有影响力的技术成果。 技术点亮生活,分享连接价值与机会。 专注AI落地实战,陪你走好技术每一步。 272

React Native 鸿蒙平行视界适配实战:平板分栏时页面宽度怎么算

平行视界列表里没有你的应用?开关打开也不分栏?真机实测把机制拆透:easyGo 声明进名单、displayModeOptions 需要 ArkTS 页面路由(RN 单页吃不到自动分栏)、系统分屏下 RN 拿到的宽度是窗口实际宽度(1440→716→478,断点自动跟随)。RN 平板适配的正确路线是响应式断点,不是平行视界。

康宝的博客 1万+

HarmonyOS 7.0 商户端实战:Column 的 space 属性和 padding 的差异

表单页里给Column写了space: 12,又在子组件上各加了margin,结果间距忽大忽小;换成padding之后,首尾留白对了,中间的间距却没了。space和padding看起来都是「留白」,但一个管兄弟之间,一个管容器内边缘。的声明把类型和适用范围写得很清楚,这篇把两者的边界和常见叠加错误讲透。

nanxuan521的专栏 158

从手表到鸿蒙电脑:一次开发多端部署的协同应用实战

本文针对 HarmonyOS「一次开发、多端部署」的落地难点,提出以设备画像、断点栅格、输入归一与状态流转为核心的适配方案。通过定义五类设备形态与统一断点体系,将显示、输入、能力、状态差异收敛为可枚举状态,结合纯函数与36项断言实现布局可测性。项目 Demo07-MultiDevice 验证了真实宽度获取、折叠屏内外屏切换与悬停态处理、跨端任务流转及输入命令归一等关键技术,强调工程化思维与三层测试策略,推动多端适配从口号走向可验证的工程实践。

wdracky的专栏 289

开源鸿蒙数据账本:我的数据我做主

本文以“数据二十条”与“数据要素×”大赛为背景,讲述开发者用鸿蒙构建个人数据可携带账本的实践。面对数据被平台锁定的困境,作者聚焦“看得见、管得住、带得走”三大能力,通过本地加密存储、颗粒化可撤回授权与通用格式一键导出,实现用户对数据的真正掌控。作品拒绝数据交易噱头,强调技术应有立场——把开关交还用户,才是对数据权利的尊重。核心结论:数据要素的终点是人的权利。

laozhangguzhang的博客 248

HarmonyOS 7.0 多设备协同实战 48:重装与恢复后,怎样拒绝历史协同令牌

把恢复视为一次新的协同加入,历史令牌就不再是便利的捷径,而是一份必须重新核对的证据。用户仍能保留真正的工作成果,系统也能拒绝过期写入、陈旧订阅和跨身份重放;这才是多设备协同在重装与恢复后值得信任的基础。当恢复过程可解释、可取消、可复查时,安全控制才不会成为用户完成工作的障碍。每次恢复都应留下足以重现判断链路的最小证据。

m0_53019445的博客 306
上一篇: 使用Flutter设置UI三方库card_settings_ui重构鸿蒙版天气预报我的页面
下一篇: 使用鸿蒙化flutter_fluttertoast替换Flutter原有的SnackBar提示弹窗
mocoding
博客等级 码龄4年 3粉丝 31原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值