我是 Flutter 新手,正在尝试从 API 获取数据。我无法从另一个类调用我的方法,即使它是导入的。我试图从 weather_service.dart 调用 weather_page.dart 中的特定方法。你能帮我吗?
weather_service.dart
import 'dart:convert';
import 'package:testapp/models/weather_model.dart';
import 'package:http/http.dart' as http;
class WeatherService {
//static const BASE_URL = 'https://api.openweathermap.org/data/2.5/forecast?q=Kutahya,tr&cnt=5&appid=e6080829dff63e16ef3e9756b2e4b0bd';
static const baseUrl = 'https://api.openweathermap.org/data/2.5/weather?';
final String apiKey; //The “final” keyword is used to declare variables whose values cannot be changed once assigned. When a variable is declared as final, it can only be assigned a value once, either at its declaration or within the constructor of the class.
WeatherService(this.apiKey){
Future<Weather> getWeather(String city, String country) async {
final response = await http.get(Uri.parse('$baseUrl?q=$city,$country&appid=$apiKey&units=metric'));
if (response.statusCode == 200) {
return Weather.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to get Data');
}
}
}
}
weather_page.dart
import 'package:flutter/material.dart';
import 'package:testapp/models/weather_model.dart';
import 'package:testapp/services/weather_service.dart';
class WeatherPage extends StatefulWidget {
const WeatherPage({super.key});
@override
State<WeatherPage> createState() => _WeatherPageState();
}
class _WeatherPageState extends State<WeatherPage> {
//set api key
final _weatherService = WeatherService('e6080829dff63e16ef3e9756b2e4b0bd');
Weather? _weather; //imported from models/weather_model
//set city and country
String city = 'Kutahya'; //You may use Geolocator to get them automatically also.
String country = 'tr';
//get data
_fetchWeather() async {
try {
final weather = await _weatherService.getWeather(city, country);
setState(() {
_weather = weather;
});
}
catch (e){
print(e);
}
}
@override
Widget build(BuildContext context) {
return const Scaffold();
}
}
我尝试从 weather_service.dart 调用名为 apiKey 的变量并且它有效。我想它导入正确,也许我的方法有问题。谢谢各位的解答。
您可以通过这样做来修复
class WeatherService {
//static const BASE_URL = 'https://api.openweathermap.org/data/2.5/forecast?q=Kutahya,tr&cnt=5&appid=e6080829dff63e16ef3e9756b2e4b0bd';
static const baseUrl = 'https://api.openweathermap.org/data/2.5/weather?';
final String apiKey;
WeatherService({required this.apiKey});
Future<Map<String, dynamic>> getWeather(String city, String country) async {
final response = await http.get(Uri.parse('$baseUrl?q=$city,$country&appid=$apiKey&units=metric'));
if (response.statusCode == 200) {
return jsonDecode(response.body);
} else {
throw Exception('Failed to get Data');
}
}
}