我试图从开放的天气API向flutter用户界面传递数据。我认为这与我在哪里初始化城市名称变量有关,因为它在每次刷新应用程序时都会重新构建,并且只加载原始字符串而不是我放在文本字段中的城市。我如何修复此代码,以便我可以使用新的城市名称从API中提取信息。
import 'package:flutter/material.dart';
import 'package:weather_solo/logic/get_weather.dart';
//import 'logic/additional_information_info.dart';
import 'logic/weather_forecast_time.dart';
class WeatherHomePage extends StatefulWidget {
const WeatherHomePage({super.key});
@override
State<WeatherHomePage> createState() => _WeatherHomePageState();
}
class _WeatherHomePageState extends State<WeatherHomePage> {
TextEditingController cityNameController = TextEditingController();
GetWeather getWeather = GetWeather();
String cityName = 'Hamilton';
late Future<Map<String, dynamic>> weather = getWeather.getCurrentWeather(cityName);
// late int iconID = weather['list'][0];
//list[0].weather[0].id
@override
void initState() {
super.initState();
weather = getWeather.getCurrentWeather(cityName);
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text('My Weather App',
style: TextStyle(
fontSize: 20,
),),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Card(
elevation: 10,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
TextField(
controller: cityNameController,
decoration: const InputDecoration(
hintText: 'Please Enter City Name Here',
border: OutlineInputBorder()
),
),
ElevatedButton(onPressed: () {
setState(() {
cityName = cityNameController.text;
cityNameController.clear();
getWeather.getCurrentWeather(cityName);
});
},
style: const ButtonStyle(
elevation: MaterialStatePropertyAll(10),
backgroundColor:
MaterialStatePropertyAll(Colors.red),
foregroundColor: MaterialStatePropertyAll(Colors.black),
),
child: const Text(
'Choose City'
),
),
],
),
),
),
// Flex for weather data, needs to be wrapped in a FutureBuilder as this is the section that will update
FutureBuilder(
future: weather,
builder: (context, snapshot) {
if(snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator.adaptive(),
);
}
if (snapshot.hasError) {
return Center(
child: Text(snapshot.error.toString()),
);
}
final data = snapshot.data!;
final currentWeatherData = data['list'][0];
final currentIcon = currentWeatherData['weather'][0]['id'];
return Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Card(
elevation: 10, //Main weather data card
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
const SizedBox(width: double.infinity,),
Text(cityName,
style: const TextStyle(
fontSize: 15,
),),
const SizedBox(height: 10,),
Text('Weather icon code $currentIcon Rain',
style: const TextStyle(
fontSize: 10
),),
const SizedBox(
height: 5,
),
const Icon(Icons.cloud,
size: 20,),
const SizedBox(height: 5,),
const Text('27 °C',
style: TextStyle(
fontSize: 20
),) //Hold down left alt and numpad 0176 for degree symbol
],
),
),
// Wetaher data time forecast
SizedBox(
height: 100,
child: ListView.builder(itemCount: 5,scrollDirection: Axis.horizontal,itemBuilder: (context ,index) {
return const WeatherForecastTime(time: '09.00', icon: Icons.sunny, desctription: 'Sunny',);
},
),
),
//Additional information
// const Row(
// mainAxisAlignment: MainAxisAlignment.spaceAround,
// children: [
// AdditionalInformationInfo(title: 'Humidity', icon: Icons.water_drop, stats: '4757',),
// AdditionalInformationInfo(title: 'Wind Speed', icon: Icons.air, stats: 'Fast',),
// AdditionalInformationInfo(title: 'Pressure', icon: Icons.umbrella, stats: '775',)
// ],
// ),
],
),
);
}
)
],
),
),
),
);
}
}
个字符
2条答案
按热度按时间vyu0f0g11#
这个修好了
字符串
lrpiutwd2#
您遇到的问题是由于初始化cityName变量的位置。正如您提到的,它是在类级别初始化的,这导致它在小部件的整个生命周期中保持其原始值,即使在更新文本字段之后也是如此。要解决此问题并确保使用更新的城市名称来获取天气数据,您应该将API调用移动到ElevatedButton的onPressed方法中的getCurrentWeather。
字符串