Home > Software engineering >  The argument type 'Future<ArticleModel?>' can't be assigned to the parameter ty
The argument type 'Future<ArticleModel?>' can't be assigned to the parameter ty

Time:12-22

I'm trying to save in cache of the articles that I'm fetching through the code above Link API Service, But I get an error in the FutureBuilder of the search icon to search articles in the Homepage telling me "The argument type 'Future<ArticleModel?>' can't be assigned to the parameter type 'Future<List>?'" Can anybody give me a hande to figure out this issue? Thank you in advance

enter image description here

ArticleModel

class ArticleModel with ChangeNotifier{
  int id;
  String? urlImage;
  String? urlImageSource;
  String? title;
  final String? description;

  ArticleModel({
    required this.id,
    required this.urlImage,
    required this.urlImageSource,
    required this.title,
    required this.description,
  });

  factory ArticleModel.fromJson(Map<String, dynamic> parsedJson) => ArticleModel(
    id:             parsedJson["id"],
    urlImage:       parsedJson["_embedded"]["wp:featuredmedia"][0]["link"],
    urlImageSource: parsedJson["_embedded"]['wp:featuredmedia'][0]["media_details"]["sizes"]["thumbnail"]["source_url"],
    title:          parsedJson["title"]["rendered"].replaceAll("&#8217;", "'").replaceAll("<p>", "").replaceAll("</p>", ""),
    description:    parsedJson['content']['rendered'],
  );

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['id']             = id;
    data['urlImage']       = urlImage;
    data['urlImageSource'] = urlImageSource;
    data['title']          = title;
    data['desciption']     = description;
    //date:['urlImage'] != null ? ['urlImage'].toString().replaceFirst('https:', 'urlImageSource') : null;
    return data;
  }
}

Link API Service

class ApiNewsPage {
 final String url = newsJsonLink; // Link news
 Future<ArticleModel?> getNewsArticles() async {
   String nameDB = "articledata.json";
   var dir = await getTemporaryDirectory();

   File file = File(dir.path   "/"   nameDB);
   if(file.existsSync()) {
     print("Loading Articles from cache");
     var jsonData = file.readAsStringSync();
     ArticleModel response = ArticleModel.fromJson(json.decode(jsonData));
     return response;
   } else {
       print("Fetching articles from API internet");
       var response = await http.get(Uri.parse(url));
       if (response.statusCode == 200) {
         var jsonArticle = response.body;
         ArticleModel res = ArticleModel.fromJson(json.decode(jsonArticle));
         /// save json in local file
         file.writeAsStringSync(jsonArticle, flush: true, mode: FileMode.write);
         return res;
       }
   }
 }
} 

FutureBuilder search icon for articles

actions: <Widget>[
              /// First search icon
              FutureBuilder<List>(
                  future: categoryNews.getNewsArticles(),
                  builder: (context, snapshot) { // AsyncSnapshot
                    if (snapshot == null || !snapshot.hasData || snapshot.connectionState != ConnectionState.done) {
                      return IconButton(
                        icon: const Icon(Icons.search, color: Colors.white,),
                        onPressed: () {
                          Navigator.of(context).push(MaterialPageRoute(
                              builder: (context)=> SearchBar(posts: _posts,)
                          ));
                        },
                      );
                    }
                    return IconButton(
                      icon: const Icon(
                        Icons.search,
                        color: Colors.white,
                      ),
                      onPressed: () {
                        Navigator.of(context).push(
                          MaterialPageRoute(
                            builder: (context) => SearchBar(
                              posts: snapshot.data!,
                            ),
                          ),
                        );
                      },
                    );
                  }),
            ],```

CodePudding user response:

Try the following code:

actions: <Widget>[
              /// First search icon
              FutureBuilder<ArticleModel?>(
                  future: categoryNews.getNewsArticles(),
                  builder: (context, snapshot) { // AsyncSnapshot
                    if (snapshot == null || !snapshot.hasData || snapshot.connectionState != ConnectionState.done) {
                      return IconButton(
                        icon: const Icon(Icons.search, color: Colors.white,),
                        onPressed: () {
                          Navigator.of(context).push(MaterialPageRoute(
                              builder: (context)=> SearchBar(posts: _posts,)
                          ));
                        },
                      );
                    }
                    return IconButton(
                      icon: const Icon(
                        Icons.search,
                        color: Colors.white,
                      ),
                      onPressed: () {
                        Navigator.of(context).push(
                          MaterialPageRoute(
                            builder: (context) => SearchBar(
                              posts: snapshot.data!,
                            ),
                          ),
                        );
                      },
                    );
                  }),
            ],

CodePudding user response:

You used the generic for FutureBuilder, but your function returns a Future<ArticleModel?> type. I don't know how your ArticleModel class is declared, but as I understand it, you must have a list of articles inside this model. Get it from snapshot.date insise FutureBuilder

  • Related