You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 02:25:09