【问题标题】:flutter weather api is'nt work the snapshot.data is showing error颤振天气API不起作用快照。数据显示错误
【发布时间】:2021-11-03 07:35:12
【问题描述】:

Main.dart

import 'package:flutter/material.dart';
import 'package:flutter_application_1/currentWeather.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: CurrentWeatherPage(),
    );
  }
}

models/weather.dart

class Weather {
  final double temp;
  final double feelslike;
  final double low;
  final double high;
  final double description;

  Weather({ required this.temp, required this.feelslike, required this.low, required this.high, required this.description});

  factory Weather.fromjson(Map<String, dynamic>json) {
    return Weather(
      temp: json['main']['temp'].toDouble(),
      feelslike: json['main']['feels_like'].toDouble(),
      low: json['main']['temp_min'].toDouble(),
      high: json['main']['temp_max'].toDouble(),
      description: json['weather'][0]['description'],
    );
  }
}

currentWeather.dart

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:flutter_application_1/models/weather.dart';

class CurrentWeatherPage extends StatefulWidget{

  @override
  _CurrentWeatherPageState createState() => _CurrentWeatherPageState();
}

class _CurrentWeatherPageState extends State<CurrentWeatherPage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: FutureBuilder(
          builder: (context, snapshot){
            // ignore: unnecessary_null_comparison
            if (snapshot != null){
              Weather _weather = snapshot.data;
              // ignore: unnecessary_null_comparison
              if (_weather == null){
                return Text("ERROR GETING WEATHER");
              } else {
                return weatherBox(_weather);
              }
            } else{
              return CircularProgressIndicator();
            }
          },
          future: getCurrentWeather(),
        ),
        ),
    );
  }  

  Widget weatherBox(Weather _weather){
    return Column(
      children: <Widget>[
        Text("${_weather.temp}°c"),
        Text("${_weather.description}"),
        Text("${_weather.feelslike}°c"),
        Text("H:${_weather.high}°c L:${_weather.low}°c"),
      ],
    );
  }
}

Future getCurrentWeather() async {
  Weather weather;
  String city = "chennai";
  String apikey = "safdgfdsgvf";
  var url = Uri.parse("api.openweathermap.org/data/2.5/weather?q=$city&appid=$apikey");

  final response = await http.get(url);

  if (response.statusCode == 200) {
    weather = Weather.fromjson(jsonDecode(response.body));
  }else {
    weather = Weather.fromjson(jsonDecode(response.body));
  }
   return weather;
}

在 currentWeather.dart 中

Weather _weather = snapshot.data;

snapshot.data 显示错误:“对象?”类型的值不能分配给“天气”类型的变量。 尝试更改变量的类型,或将右侧类型转换为 'Weather'.dart(invalid_assignment)

我该如何解决这个错误

【问题讨论】:

  • 您应该修复它们,而不是忽略编译器警告。

标签: flutter snapshot openweathermap weather-api flutter-android


【解决方案1】:

您应该将 Map 对象的 snapshot.data 转换为 Weather 对象。

Weather _weatherl = Weather.fromjson(snapshot.data!.data());
// Output of this code is depend on how is your data structured in the database and Weather model you have defined here.

【讨论】:

    猜你喜欢
    • 2021-02-20
    • 2021-12-16
    • 2020-09-19
    • 2020-04-08
    • 1970-01-01
    • 2022-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多