Вызов метода из другого класса (Flutter)Android

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Вызов метода из другого класса (Flutter)

Сообщение Anonymous »

Я новичок в Flutter и пытаюсь получить данные из API. Я не могу вызвать свой метод из другого класса, даже если он импортирован. Я пытаюсь вызвать этот конкретный метод в weather_page.dart из weather_service.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 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 createState() => _WeatherPageState();
}

class _WeatherPageState extends State {

//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();
}
}
Я попытался вызвать переменную с именем apiKey из weather_service.dart, и это сработало. Я полагаю, что он импортирован правильно, возможно, что-то не так с моим методом. Спасибо за ответы.

Подробнее здесь: https://stackoverflow.com/questions/790 ... ss-flutter
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»