Type 'Null' is not a subtype of type 'String' in type cast - Flutter

Viewed 4869

I am making a mistake somewhere, unfortunately after displaying the results everything should work but it does not.

I have tried in many ways, but unfortunately only CircularProgressIndicator still appears.Everything seems to be properly done but unfortunately something is missing.

Any help is greatly appreciated!

enter image description here

 class ApiService {
 final endPointUrl = "newsapi.org";
final client = http.Client();

  Future<List<Article>> getArticle() async {

final queryParameters = {
  'country': 'us',
  'category': 'business',
  'apiKey': 'd74673ec25dd468d94ab03035fa53ff7'
};

final uri = Uri.https(endPointUrl, '/v2/top-headlines', queryParameters);
final response = await client.get(uri);
Map<String, dynamic> json = jsonDecode(response.body);
print(response.body);
List<dynamic> body = json['articles'];
print(body);
List<Article> articles = body.map((dynamic item) => Article.fromJson(item)).toList();
print(articles);
return articles;

  }
}

And classes:

class Article {
Source source;
 // String author;
  String title;
 String description;
 String url;
 String urlToImage;
 String publishedAt;


   Article(
     {required this.source,
    // required this.author,
    required this.title,
    required this.description,
    required this.url,
    required this.urlToImage,
    required this.publishedAt,
   });

factory Article.fromJson(Map<String, dynamic> json) {
return Article(
  source: Source.fromJson(json['source']),
  // author: json['author'] as String,
  title: json['title'] as String,
  description: json['description'] as String,
  url: json['url'] as String,
  urlToImage: json['urlToImage'] as String,
  publishedAt: json['publishedAt'] as String,
  );
}
 }


class Source {
  // String id;
   String name;

  Source({ required this.name});

  factory Source.fromJson(Map<String, dynamic> json) {
    return Source(
       // id: json['id'] as String,
        name: json['name']as String);
     }
   }

flutter code:

  Widget mainArticles(BuildContext context) {
return FutureBuilder(
  future: client.getArticle(),
  builder: (BuildContext context, AsyncSnapshot<List<Article>> snapshot) {
    if (snapshot.hasData) {
      List<Article> articles = snapshot.data!;
      return ListView.builder(
          itemCount: articles.length,
          itemBuilder: (context, index) => customListTile(articles[index], context)
      );
    }
    return Center(
      child: CircularProgressIndicator(),
    );
  },
);
  }
2 Answers

Two options :

  1. Either make the variable nullable in declaration statement : String varName -> String? varName

  2. Use of ?? operator in assignment of statement : urlToImage: json['urlToImage'] as String, -> urlToImage: json['urlToImage'] ?? "", //assign an empty string if the first value is null.

You have json['urlToImage'] as String, but in your data json['urlToImage'] is null. You should therefore change the urlToImage in your model to String? and cast it to String? instead of String to make it nullable.

You can read more about null safety in the documentation

Related