not Showing cityname and temperature

I am developing a weather application in Flutter, but unfortunately, I have encountered these bugs.unfortunately in home.dart _weather is null andIt does not show this is api_model.dart flie

import 'package:flutter/material.dart';

class Weather {
  final String? cityName;
  final double? temp;
  final List<WeatherData>? weatherdesc;
  final double? humidity;

  Weather({
    required this.cityName,
    required this.temp,
    required this.weatherdesc,
    required this.humidity,
  });

  factory Weather.fromJson(Map<String, dynamic> json) {
    return Weather(
      cityName: json['name'],
      temp: (json['main']['temp'] as num).toDouble(),
      weatherdesc: (json['weather'] as List<dynamic>)
          .map((e) => WeatherData.fromJson(e as Map<String, dynamic>))
          .toList(),
      humidity: (json['main']['humidity'] as num).toDouble(),
    );
  }
}

@immutable
class WeatherData {
  final int? id;
  final String? main;
  final String? description;
  final String icon;

  WeatherData({
    required this.id,
    required this.main,
    required this.description,
    required this.icon,
  });

  factory WeatherData.fromJson(Map<String, dynamic> json) {
    return WeatherData(
      id: json['id'],
      main: json['main'],
      description: json['description'],
      icon: json['icon'],
    );
  }
}

and this is weather_services file

import 'package:geolocator/geolocator.dart';
import 'package:geocoding/geocoding.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:weather_app/model/api_model.dart';
import 'package:logger/logger.dart';

final logger = Logger();

class WeatherServices {
  final String apiKey;

  WeatherServices(this.apiKey);

  Future<String> getCurrentCity() async {
    logger.d('Checking location permission');
    LocationPermission permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        logger.e("Location permission denied");
        throw Exception("Location permission denied");
      }
    }
    if (permission == LocationPermission.deniedForever) {
      logger.e("Location permission denied forever");
      throw Exception("Location permission denied forever");
    }

    logger.d('Getting current position');
    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
    logger.d('Current position: ${position.latitude}, ${position.longitude}');

    try {
      List<Placemark> placemarks =
          await placemarkFromCoordinates(position.latitude, position.longitude);
      logger.d('Placemarks length: ${placemarks.length}');

      if (placemarks.isNotEmpty) {
        String? city = placemarks[0].locality;
        logger.d('City found: $city');
        return city ?? "Unknown location";
      } else {
        logger.e('No placemarks found');
        throw Exception("No placemarks found");
      }
    } catch (e) {
      logger.e('Geocoding Error: $e');
      throw Exception("Geocoding Error: $e");
    }
  }

  Future<Weather> getWeather(String cityName) async {
    final url =
        'https://api.openweathermap.org/data/2.5/weather&q=$cityName&appid=$apiKey&units=metric';
    logger.d('Fetching weather data from: $url');
    final response = await http.get(Uri.parse(url));

    if (response.statusCode == 200) {
      logger.d('Weather data fetched successfully');
      logger.d("cityName is {$Weather.cityName}");
      return Weather.fromJson(jsonDecode(response.body));
    } else {
      logger.e('Failed to load weather data: ${response.statusCode}');
      throw Exception('Failed to load weather data');
    }
  }
}

and finally this is home file

import 'package:flutter/material.dart';
import 'package:logger/logger.dart';
import 'package:weather_app/model/api_model.dart';
import 'package:weather_app/services/weather_service.dart';

class Home extends StatefulWidget {
  const Home({super.key});

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  final _weatherService = WeatherServices("api-key");
  Weather? _weather;

  final logger = Logger();

  Future<void> _fetchWeather() async {
    logger.d("Fetching weather...");
    try {
      final cityName = await _weatherService.getCurrentCity();
      logger.d('City: $cityName');

      final weather = await _weatherService.getWeather(cityName);
      setState(() {
        _weather = weather;
      });
    } catch (e) {
      logger.e("Failed to fetch weather");
    }
  }

  @override
  void initState() {
    super.initState();
    _fetchWeather();
  }

  @override
  Widget build(BuildContext context) {
    var height = MediaQuery.of(context).size.height;
    var width = MediaQuery.of(context).size.width;

    return Scaffold(
      body: Stack(children: [
        Container(
          width: double.infinity,
          height: double.infinity,
          decoration: const BoxDecoration(
              image: DecorationImage(
                  image: AssetImage(
                    "assets/images/background.png",
                  ),
                  fit: BoxFit.cover)),
        ),
        if (_weather != null)
          Positioned(
            top: 120,
            left: 130,
            child: Text(
              _weather!.cityName ?? "null",
              style: const TextStyle(
                  color: Colors.white,
                  fontSize: 20,
                  fontWeight: FontWeight.bold),
            ),
          ),
        if (_weather != null)
          Positioned(
            top: 160,
            left: 130,
            child: Text(
              '${_weather?.temp?.round() ?? "N/A"}°C',
              style: const TextStyle(
                  color: Colors.white,
                  fontSize: 20,
                  fontWeight: FontWeight.bold),
            ),
          ),
        Positioned(
          top: 130,
          bottom: 0,
          right: 0,
          left: 0,
          child: Container(
            width: width / 1.3,
            height: height / 1.3,
            decoration: const BoxDecoration(
                image: DecorationImage(
              image: AssetImage(
                "assets/images/House.png",
              ),
            )),
          ),
        ),
        Positioned(
          bottom: 0,
          left: 0.0,
          right: 0.0,
          child: Container(
            width: double.infinity,
            height: height / 2.5,
            decoration: const BoxDecoration(
                gradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [
                      Color(0xFF2E335A),
                      Color(0xFF48319D),
                    ]),
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(55),
                  topRight: Radius.circular(55),
                )),
          ),
        ),
      ]),
    );
  }
}

where is my problem? thanks for help!

i want to help me to show cityname and temperature

New contributor

keyvan bvb is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật