标题:Flutter 入门实战:构建一个简单的天气应用
引言
随着移动应用开发需求的不断增长,跨平台框架成为开发者关注的焦点。Flutter 作为 Google 推出的 UI 工具包,凭借高性能、高保真和“一次编写,多端运行”的优势,迅速在开发者社区中崛起。本文将带你从零开始,使用 Flutter 构建一个简单的天气应用,并结合实际代码演示核心概念。
一、环境准备
在开始前,请确保已安装以下工具:
- Flutter SDK(推荐版本 3.19 或以上)
- Dart SDK(随 Flutter 自动安装)
- 编辑器:VS Code 或 Android Studio
- 模拟器或真机用于调试
创建项目:
flutter create weather_appcdweather_app二、项目结构概览
Flutter 项目的基本结构如下:
lib/ ├── main.dart # 应用入口 └── screens/ └── weather_screen.dart # 天气页面我们将在main.dart中启动应用,并在weather_screen.dart中实现主要逻辑。
三、编写代码:实现一个简单天气界面
1.main.dart—— 应用入口
// lib/main.dartimport'package:flutter/material.dart';import'screens/weather_screen.dart';voidmain(){runApp(constMyApp());}classMyAppextendsStatelessWidget{constMyApp({super.key});@overrideWidgetbuild(BuildContext context){returnMaterialApp(title:'天气应用',theme:ThemeData(primarySwatch:Colors.blue,useMaterial3:true,),home:constWeatherScreen(),debugShowCheckedModeBanner:false,// 隐藏右上角 debug 标签);}}2. 创建天气页面:weather_screen.dart
// lib/screens/weather_screen.dartimport'package:flutter/material.dart';classWeatherScreenextendsStatefulWidget{constWeatherScreen({super.key});@overrideState<WeatherScreen>createState()=>_WeatherScreenState();}class_WeatherScreenStateextendsState<WeatherScreen>{// 模拟天气数据String cityName="北京";int temperature=22;String description="晴朗";// 模拟刷新天气void_refreshWeather(){setState((){// 随机生成温度(15~30°C)temperature=(15+(15*Math.Random().nextDouble())).toInt();// 随机描述finaldescriptions=["晴朗","多云","小雨","阴天","雷阵雨"];description=descriptions[Random().nextInt(descriptions.length)];});}@overrideWidgetbuild(BuildContext context){returnScaffold(appBar:AppBar(title:constText("🌤️ 天气预报"),centerTitle:true,),body:Container(padding:constEdgeInsets.all(20),child:Column(mainAxisAlignment:MainAxisAlignment.center,children:[// 城市名称Text(cityName,style:constTextStyle(fontSize:32,fontWeight:FontWeight.bold),),constSizedBox(height:20),// 温度Text('$temperature°C',style:constTextStyle(fontSize:64,color:Colors.orange),),constSizedBox(height:10),// 天气描述Text(description,style:constTextStyle(fontSize:20,color:Colors.grey),),constSizedBox(height:40),// 刷新按钮ElevatedButton.icon(onPressed:_refreshWeather,icon:constIcon(Icons.refresh),label:constText("更新天气"),style:ElevatedButton.styleFrom(padding:constEdgeInsets.symmetric(horizontal:30,vertical:15),),),],),),);}}⚠️ 注意:请在文件顶部添加导入:
import'dart:math';
四、运行应用
在项目根目录运行以下命令:
flutter run你将看到一个简洁美观的天气界面,点击“更新天气”按钮后,温度和天气描述会随机变化,得益于 Flutter 的热重载(Hot Reload),你可以在修改代码后几乎立即看到效果。
五、核心概念解析
Widget 架构
Flutter 中一切皆为 Widget。Scaffold提供页面骨架,AppBar是顶部栏,Column用于垂直布局。状态管理(setState)
_refreshWeather方法中调用setState(),通知 Flutter 重新构建 UI,实现动态更新。Material Design 组件
使用ElevatedButton、Text等 Material 风格组件,自动适配 Android 和 iOS 视觉规范。布局与间距
SizedBox用于控制元素间距离,Padding和Center实现精准排版。
六、扩展建议(进阶方向)
- ✅ 接入真实 API:使用 OpenWeatherMap API 获取实时天气。
- ✅ 添加输入框让用户搜索城市。
- ✅ 使用
http包请求网络数据:# pubspec.yamldependencies:http:^1.0.0 - ✅ 引入状态管理方案如
Provider或Riverpod管理复杂状态。
七、总结
通过这个简单的天气应用,我们实践了 Flutter 的基本开发流程:
- 使用 Dart 编写逻辑
- 通过 Widget 构建 UI
- 利用
setState实现交互响应 - 快速预览与调试
Flutter 不仅让跨平台开发变得高效,更以出色的性能和灵活的设计赢得了广泛青睐。无论你是初学者还是资深开发者,掌握 Flutter 都将为你打开通往现代多端应用开发的大门。
🚀 下一步建议:
尝试将本项目接入真实天气 API,并支持多城市切换,打造属于你的完整跨平台天气 App!
GitHub 示例仓库参考:github.com/example/flutter-weather-app(模拟地址)
本文代码可在 Flutter 3.x 环境下正常运行,SDK 支持 Android、iOS 与 Web 平台。