如何从模型实例(具有来自 api 的值)传递数据并将其提供给 Text() 小部件?但请没有列表视图的示例。我只需要将值提供给 Text 小部件。
在第一个块中,我的天气实例有一个值,但我不知道如何将这个值提供给我的 Text 小部件。如果你能帮助我,我将不胜感激
home.dart 文件:
import 'package:flutter/material.dart';
import 'package:weather_mix_app/models/weather_model.dart';
import 'package:weather_mix_app/services/weather.dart';
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
List<WeatherModel> weather = new List<WeatherModel>();
@override
void initState() {
super.initState();
setupWeather();
}
setupWeather() async {
Weather weatherInstance = Weather();
await weatherInstance.fetchData();
weather = weatherInstance.weather;
}
@override
Widget build(BuildContext context) {
return Container(child: Text('WHAT I NEED TO WRITE...'));
}
}
我的 weather.dart(从 api 获取数据)
import 'dart:convert';
import 'package:http/http.dart';
import 'package:weather_mix_app/models/weather_model.dart';
class Weather {
List<WeatherModel> weather = [];
Future<void> fetchData() async {
try {
Response response = await get(
'http://api.weatherstack.com/current?access_key=3327f40525a4577b7d0a75aea0c7d44f&query=New%20York');
Map jsonData = jsonDecode(response.body);
WeatherModel weatherModel = WeatherModel(
description: jsonData['current']['weather_descriptions'],
temp: jsonData['current']['temperature'],
feels_like: jsonData['current']['feelslike'],
query: jsonData['request']['query']);
weather.add(weatherModel);
print(weather);
} catch (e) {
print('caught error! $e');
}
}
}
和我的 weather_model.dart
class WeatherModel {
dynamic description;
dynamic temp;
dynamic feels_like;
dynamic query;
WeatherModel({this.description, this.temp, this.feels_like, this.query});
}