flutter - 有没有办法可以在 Dart 中使用 Future 值来填充文本字段?
问题描述
我一直在学习 Dart 并且正在为实践创建天气应用程序,我成功地创建了 UI,我使用了 Dark Sky 天气 API,因为它有 7 天的天气预报,但没有走漫长的解码 json 和模型的道路,我使用了黑暗天空图书馆。这是API的代码
Future<Null> getWeather() async {
Location location = Location();
await location.getCurrentPosition();
var darksky = DarkSkyWeather(
MY_API_KEY,
units: Units.SI,
language: Language.English,
);
var forecast = await darksky.getForecast(
location.latitude, location.longitude, excludes: [
Exclude.Hourly,
Exclude.Minutely,
Exclude.Alerts,
Exclude.Flags
]);
print(forecast.currently.temperature.round());
print(forecast.daily.data[0].temperatureMax);
}
我想在函数之外使用预测变量,并在包中的其他数据中填充诸如湿度温度之类的文本字段。我怎样才能访问它?任何帮助将不胜感激 。谢谢
解决方案
看看这段代码
class _MyHomePageState extends State<MyHomePage> {
String _data; // This holds the data to be shown
@override
void initState() {
_data = "Press the button"; // This is the initial data // Set it in initState because you are using a stateful widget
super.initState();
}
// Call this to set the new data
void setData() {
setState(() { // Remember to use setState() else the changes won't appear
_data = 'Hello World';
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Message',
),
Text(
'$_data', // See how the data is fed into this text widget
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: setData, // When I press the button, the new data is set
child: Icon(Icons.send),
),
);
}
}
输出:
最初:
按下按钮后:
在你的代码中做同样的事情。
// Your code modified a bit
// Make sure this is a stateful widget because you are changing values
double _tempNow; // Declare two vars inside the class
double _tempMax;
// Your initState
@override
void initState() {
_tempNow = 0; // Initial values
_tempMax = 0;
super.initState();
}
// Build method
@override
Widget build(BuildContext context) {
// Your layout Code.....
Text(
'Current: $_tempNow' // Here you set the tempNow
),
......
Text(
'Maximum: $_tempMax' // and tempMax in the text widgets
),
// End
}
Future<Null> getWeather() async {
Location location = Location();
await location.getCurrentPosition();
var darksky = DarkSkyWeather(
"8810b3633934b8c1975c51a2311dc1d0",
units: Units.SI,
language: Language.English,
);
var forecast = await darksky.getForecast(
location.latitude, location.longitude, excludes: [
Exclude.Hourly,
Exclude.Minutely,
Exclude.Alerts,
Exclude.Flags
]);
// Change the values here.
// After the data is fetched, The changes will be made automatically
setState(() {
_tempNow = forecast.currently.temperature.round();
_tempMax = forecast.daily.data[0].temperatureMax;
});
}
以非常相似的方式,您也可以使用文本字段。在这种情况下,您将需要使用TextEditingController并在那里设置文本,但在您的情况下,您似乎需要只读文本来向用户显示信息,因此一个简单的 Text 小部件就足够了