Flutter跨类调用方法异常:无法调用WeatherService的getWeather方法
问题解决:无法调用WeatherService中的getWeather方法
问题出在getWeather方法的定义位置——你把它写在了WeatherService的构造函数内部,这让它变成了构造函数的局部函数,不属于类的公开成员,所以外部实例无法访问。
修正后的weather_service.dart代码
import 'dart:convert'; import 'package:testapp/models/weather_model.dart'; import 'package:http/http.dart' as http; class WeatherService { static const baseUrl = 'https://api.openweathermap.org/data/2.5/weather?'; final String apiKey; WeatherService(this.apiKey); // 构造函数单独定义,不要嵌套方法 // 将getWeather作为类的成员方法 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'); } } }
修改说明
把getWeather方法从构造函数中提取出来,直接作为WeatherService类的成员方法,这样weather_page.dart中的_weatherService实例就能正常调用getWeather方法了。
你原来的构造函数写法没问题,但嵌套方法会导致作用域错误,调整后就能解决调用问题。
内容的提问来源于stack exchange,提问作者Buğra
相关产品推荐
相关产品推荐

