Flutter bloc cubit test knowdge

Flutter Bloc Simple Api

This project is using weather api for featch data and display based on user input data

Weather Cubit

class WeatherCubit extends Cubit<WeatherState> {
  //_weatherReposotory object for fetch data from Reposotory
  final WeatherReposotory _weatherReposotory;

  WeatherCubit(
    this._weatherReposotory,
  ) : super(const WeatherInitial());

  //getWeather function use for get weather data from Reposotory.
  Future<void> getWeather(String cityName) async {
    //notify frontend to Weather loading state
    emit(const WeatherLoading());

    try {
      final weather = await _weatherReposotory.getWeatherLocationData(cityName);
      //notify frontend to Weather loaded state with weather data
      emit(WeatherLoaded(weather, cityName));
    } on SocketException {
      //notify frontend to WeatherError state with SocketException
      emit(const WeatherError("400"));
    } catch (e) {
      final failure = e as Failure;
      //notify frontend to WeatherError state with failure message
      emit(WeatherError(failure.message));
    }
  }
}

Weather Repository

class WeatherReposotory {
  //api object use for fetch data from api
  final WeatherApi api;
  WeatherReposotory({required this.api});

  //getWeatherLocationData function is asyncrones method and using fetch data and return data to cubit
  Future<dynamic> getWeatherLocationData(String cityName) async {
    //rawWeather get response from api using user enter city name
    final Response rawWeather = await api.getWeatherRawData(cityName);
    if (rawWeather.statusCode == 200) {
      //decode jason response body and map body data
      Map<String, dynamic> weatherMap = jsonDecode(rawWeather.body);
      //Map cityname and temp using weather model and return weather data
      var weather = Weather.fromJson(weatherMap);
      return weather;
    } else {
      throw const Failure(message: '404');
    }
  }
}

Weather Api

class WeatherApi {
  //base url. url end point
  static const String _baseUrl =
      "http://api.openweathermap.org/data/2.5/weather?q=";

  //Api key
  static const String _apiKey = "01cc8328d04c516c03c84af29cd9c0d9";
  final http.Client _client;

  WeatherApi({http.Client? client}) : _client = client ?? http.Client();

  void dispose() {
    _client.close();
  }

  //Fectch weather data from api
  Future<dynamic> getWeatherRawData(String cityName) async {
    final url = '$_baseUrl$cityName&appid=$_apiKey';

    final response = await _client.post(
      Uri.parse(url),
    );
    return response;
  }
}
```# flutter_bloc_cubit_test_knowdge

GitHub

View Github