dart 从API接收数据的问题,数据可能是字符串或null

uajslkp6  于 2023-04-27  发布在  其他
关注(0)|答案(1)|浏览(139)

我使用tmdb来获取电影数据,所有的事情工作正常,直到尝试从流行电影的第三页获取电影,这里是我得到的错误
发生异常:类型“Null”不是类型“String”stackTrace的子类型:#0
这是fetch函数,返回错误:

class DioApiClient implements ApiClient {
  final Dio dio = Dio();
  final Api api = Api();

  @override
  Future<List<MovieModel>> getDataFrom(String endPoint,
      {Map<String, dynamic>? params}) async {
    final String url = "${api.baseURL}/$endPoint";
    log("from api client :$url/$params");

    Map<String, dynamic> queryParameters = {
      'api_key': api.apiKey,
      // 'language': 'en-US',
    };
    if (params != null) {
      queryParameters.addAll(params);
    }

    try {
      final response = await dio.get(url, queryParameters: queryParameters);

      log(" status code : ${response.statusCode}");
      if (response.statusCode == 200) {
        final Map<String, dynamic> data = response.data;
        final List<dynamic> results = data['results'];
        final List<MovieModel> movies =
            results.map((dynamic movie) => MovieModel.fromJson(movie)).toList();

        return movies;
      }

      
    } catch (error, stacktrace) {
      log("Exception occured: $error stackTrace: $stacktrace");
      throw Exception('Failed to load data ');
    }
    throw Exception("data not found");
  }
}

这是电影模型:

import '../../domain/entities/movie_entity.dart';

class MovieModel {
  final int id;
  final String title;
  final String overview;
  final String posterPath;
  final num voteAverage;
  final String backdropPath;
  final String releaseDate;

  MovieModel({
    required this.id,
    required this.title,
    required this.overview,
    required this.posterPath,
    required this.voteAverage,
    required this.backdropPath,
    required this.releaseDate,
  });

  factory MovieModel.fromJson(Map<String, dynamic> json) {
    return MovieModel(
      id: json['id'],
      title: json['title'],
      overview: json['overview'],
      posterPath: json['poster_path'],
      voteAverage: json['vote_average'],
      backdropPath: json['backdrop_path'],
      releaseDate: json['release_date'],
    );
  }

  MovieEntity toEntity() {
    return MovieEntity(
      id: id,
      title: title,
      overview: overview,
      posterPath: posterPath,
      voteAverage: voteAverage,
      backdropPath: backdropPath,
      releaseDate: releaseDate,
    );
  }
}

我试图使backdropPath和posterPath为空,但它的我得到了相同的行为

eqqqjvef

eqqqjvef1#

你的json可以有null值(如你在屏幕poster_path和backdrop_path中所示)。
这意味着如果posterPath: json['poster_path']为null,它将崩溃,因为你试图在一个不可为null的String中设置一个null值。你可以让你的字符串为null,或者做一个安全检查。如果你的值为null,设置默认值是一个很好的做法,就像这样:

posterPath: json['poster_path'] != null ? json['poster_path'] : "",

或者你使用短变分和??运算符:

posterPath: json['poster_path'] ?? "",

你的fromJson可以看起来像这样:

return MovieModel(
      id: json['id'] ?? 0,
      title: json['title'] ?? "",
      overview: json['overview'] ?? "",
      posterPath: json['poster_path'] ?? "",
      voteAverage: json['vote_average'] ?? 0,
      backdropPath: json['backdrop_path'] ?? "",
      releaseDate: json['release_date'] ?? "",
    );

相关问题