海北公司网站建设价格低德州极速网站建设小程序

张小明 2026/3/13 6:46:21
海北公司网站建设价格低,德州极速网站建设小程序,郑州网站建设moran,北京时间网站建设标题#xff1a;深入 Flutter 开发#xff1a;构建一个带网络请求的天气应用#xff08;含完整代码#xff09; 引言 在移动开发领域#xff0c;Flutter 凭借其高性能、跨平台能力和出色的 UI 表现力#xff0c;已成为 Google 主推的现代应用开发框架。它使用 Dart 语言…标题深入 Flutter 开发构建一个带网络请求的天气应用含完整代码引言在移动开发领域Flutter凭借其高性能、跨平台能力和出色的 UI 表现力已成为 Google 主推的现代应用开发框架。它使用 Dart 语言通过自绘引擎 Skia 实现原生级渲染支持一套代码运行在 iOS、Android、Web 和桌面端。本文将带你从零开始使用 Flutter 构建一个真实的天气查询应用涵盖 UI 布局、HTTP 请求、JSON 解析、状态管理与错误处理并附有完整可运行代码。一、环境准备确保已安装Flutter SDKv3.19Dart编辑器推荐 VS Code 或 Android Studio模拟器或真机调试设备创建项目flutter create flutter_weather_appcdflutter_weather_app二、添加依赖编辑pubspec.yaml文件添加网络请求和图标支持dependencies:flutter:sdk:flutterhttp:^1.0.0# 用于发送 HTTP 请求intl:^0.19.0# 格式化日期等可选保存后运行flutter pub get三、获取免费天气 API我们使用 OpenWeatherMap 的免费 API注册账号并获取API Key使用如下接口https://api.openweathermap.org/data/2.5/weather?q城市名appid你的APIKeyunitsmetriclangzh_cn示例响应JSON{name:Beijing,main:{temp:22.5,humidity:60},weather:[{description:晴朗,icon:01d}]}四、项目结构lib/ ├── main.dart ├── models/ │ └── weather.dart ├── services/ │ └── weather_service.dart └── screens/ └── weather_screen.dart五、完整代码实现1. 模型类models/weather.dart// lib/models/weather.dartclassWeather{finalString cityName;finaldouble temperature;finalString description;finalString iconCode;Weather({requiredthis.cityName,requiredthis.temperature,requiredthis.description,requiredthis.iconCode,});// 工厂构造函数从 JSON 创建对象factoryWeather.fromJson(MapString,dynamicjson){returnWeather(cityName:json[name],temperature:json[main][temp].toDouble(),description:json[weather][0][description],iconCode:json[weather][0][icon],);}}2. 网络服务services/weather_service.dart// lib/services/weather_service.dartimportdart:convert;importpackage:http/http.dartashttp;import../models/weather.dart;classWeatherService{finalString apiKey;WeatherService(this.apiKey);FutureWeatherfetchWeather(String city)async{finalurlUri.parse(https://api.openweathermap.org/data/2.5/weather?q$cityappid$apiKeyunitsmetriclangzh_cn);finalresponseawaithttp.get(url);if(response.statusCode200){returnWeather.fromJson(json.decode(response.body));}else{throwException(Failed to load weather data);}}}3. 主界面screens/weather_screen.dart// lib/screens/weather_screen.dartimportpackage:flutter/material.dart;import../models/weather.dart;import../services/weather_service.dart;classWeatherScreenextendsStatefulWidget{constWeatherScreen({super.key});overrideStateWeatherScreencreateState()_WeatherScreenState();}class_WeatherScreenStateextendsStateWeatherScreen{finalTextEditingController _controllerTextEditingController();Weather?_weather;bool _loadingfalse;String?_error;// 替换为你的 OpenWeatherMap API KeyfinalWeatherService serviceWeatherService(YOUR_API_KEY_HERE);void_searchWeather()async{finalcity_controller.text.trim();if(city.isEmpty)return;setState((){_loadingtrue;_errornull;});try{finalweatherawaitservice.fetchWeather(city);setState((){_weatherweather;_loadingfalse;});}catch(e){setState((){_errore.toString();_loadingfalse;});}}overrideWidgetbuild(BuildContext context){returnScaffold(appBar:AppBar(title:constText(️ 天气预报),centerTitle:true,),body:Padding(padding:constEdgeInsets.all(16.0),child:Column(children:[// 输入框 搜索按钮Row(children:[Expanded(child:TextField(controller:_controller,decoration:constInputDecoration(labelText:输入城市名称,border:OutlineInputBorder(),),onSubmitted:(_)_searchWeather(),),),constSizedBox(width:8),ElevatedButton(onPressed:_searchWeather,child:constIcon(Icons.search),),],),constSizedBox(height:20),// 加载状态if(_loading)constCircularProgressIndicator()elseif(_error!null)Text(错误: $_error,style:TextStyle(color:Colors.red[700]),)elseif(_weather!null)_buildWeatherCard(_weather!)elseconstText(请输入城市查询天气)],),),);}// 显示天气信息卡片Widget_buildWeatherCard(Weather weather){returnCard(elevation:4,child:Container(padding:constEdgeInsets.all(20),child:Column(crossAxisAlignment:CrossAxisAlignment.center,children:[Text(weather.cityName,style:constTextStyle(fontSize:28,fontWeight:FontWeight.bold),),constSizedBox(height:10),Image.network(https://openweathermap.org/img/wn/${weather.iconCode}2x.png,width:100,height:100,),Text(${weather.temperature.toStringAsFixed(1)}°C,style:constTextStyle(fontSize:40,color:Colors.orange),),Text(weather.description,style:constTextStyle(fontSize:18,color:Colors.grey),),],),),);}overridevoiddispose(){_controller.dispose();super.dispose();}}4. 入口文件main.dart// lib/main.dartimportpackage:flutter/material.dart;importscreens/weather_screen.dart;voidmain(){runApp(constMyApp());}classMyAppextendsStatelessWidget{constMyApp({super.key});overrideWidgetbuild(BuildContext context){returnMaterialApp(title:Flutter 天气应用,theme:ThemeData(primarySwatch:Colors.blue,useMaterial3:true,),home:constWeatherScreen(),debugShowCheckedModeBanner:false,);}}六、运行应用flutter run在输入框中输入城市如 “Shanghai” 或 “纽约”点击搜索即可看到实时天气信息。七、核心知识点总结技术点说明StatefulWidget用于需要动态更新的界面如加载、数据变化http.get()发送网络请求获取天气数据Future与async/await异步处理网络调用setState()触发 UI 重绘TextFormField用户输入处理JSON 解析使用factory构造函数映射 API 响应错误处理try-catch 捕获异常并友好提示八、优化建议进阶方向✅ 使用Provider/Riverpod进行全局状态管理✅ 添加地理位置定位自动获取城市✅ 支持天气图标本地缓存✅ 增加未来几天预报调用 5-day forecast API✅ 支持主题切换深色/浅色模式九、结语通过这个实战项目你已经掌握了 Flutter 应用开发的核心流程UI 构建 → 网络请求 → 数据解析 → 状态更新 → 用户交互Flutter 不仅让跨平台开发变得简单高效更以接近原生的性能和丰富的组件生态成为现代移动开发的理想选择。 下一步将本项目部署到 Web 平台flutter build web让你的天气应用在浏览器中也能运行 提示请将YOUR_API_KEY_HERE替换为你在 OpenWeatherMap 获取的真实密钥。GitHub 示例地址参考github.com/yourname/flutter-weather本文代码已在 Flutter 3.22 上测试通过支持 Android、iOS 与 Web 平台。
版权声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!

宣传网站建设实践报告wordpress伪静态作用

导读:Deepoc深算纪元,以科技之力引领智能变革。当传统设备深陷“功能固化、升级成本高”的困境,我们的具身智能模型正赋予机器以“灵魂”,让智能体能够在真实环境中感知、思考与行动,重塑人机交互。无需高额换购&#…

张小明 2026/3/5 2:35:33 网站建设

广州营销型网站建设哪家好郑州网站建设企起

Langchain-Chatchat 如何配置自动伸缩?K8s HPA 策略深度实践 在企业级 AI 应用日益普及的今天,智能问答系统早已不再是实验室里的概念,而是真正走进了客服、知识管理、内部培训等核心业务场景。Langchain-Chatchat 作为本地知识库问答系统的代…

张小明 2026/3/5 2:35:33 网站建设

密云网站开发软件开发的软件

LangFlow 与天翼云 CloudMonitor:构建可信赖的低代码 AI 应用闭环 在大模型技术加速落地的今天,越来越多企业希望将 LLM 能力融入客服、知识管理、智能助手等业务场景。但现实往往充满挑战:LangChain 的 API 层级复杂,调试成本高&…

张小明 2026/3/5 2:35:34 网站建设

怎么做网页中不显示项目符号苏州优化有限公司

可视化编排:如何让机器学习工作流开发变得像搭积木一样简单? 【免费下载链接】cube-studio cube studio开源云原生一站式机器学习/深度学习AI平台,支持sso登录,多租户/多项目组,数据资产对接,notebook在线开…

张小明 2026/3/13 6:40:59 网站建设

阿里云手机网站建设濮阳seo网站建设

人工智能助力下的软件项目反馈循环 关键词:人工智能、软件项目、反馈循环、项目管理、软件开发、机器学习、数据驱动决策 摘要:本文聚焦于人工智能助力下的软件项目反馈循环。首先介绍了软件项目反馈循环的背景,包括目的、预期读者、文档结构和相关术语。接着阐述了核心概念…

张小明 2026/3/5 2:35:37 网站建设

网站前台模板下载商务网站建设的组成包括

DeepSeek-V3 KV缓存深度优化:如何实现多轮对话的零冗余计算 【免费下载链接】DeepSeek-V3 项目地址: https://gitcode.com/GitHub_Trending/de/DeepSeek-V3 在大规模语言模型的实际部署中,多轮对话场景下的推理效率直接影响用户体验和系统成本。…

张小明 2026/3/5 2:35:37 网站建设