【问题标题】:NoSuchMethodError: Class'_InternalLinkedHashMap<String, dynamic>'has no instance method 'cast' with matching argumentsNoSuchMethodError:类 '_InternalLinkedHashMap<String, dynamic>' 没有具有匹配参数的实例方法 'cast'
【发布时间】:2021-11-07 00:46:42
【问题描述】:

我正在尝试从 newsApi 获取数据,但我似乎收到了上述错误。 包括的是我的 main.dart 代码

import 'dart:async';
import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future<List<Article>> fetchArticles(http.Client client) async {
  //final response = await client.get(Uri.parse('https://jsonplaceholder.typicode.com/Articles'));
  String link = "https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=MykEYhere";
final response = await client.get(Uri.parse(link));
  // Use the compute function to run parseArticles in a separate isolate.
  return compute(parseArticles, response.body);
}

// A function that converts a response body into a List<Article>.
List<Article> parseArticles(String responseBody) {
  final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();

  return parsed.map<Article>((json) => Article.fromJson(json)).toList();
}

class Article {
  final String author;
  final String title;
  final String description;
  final String url;
  final String urlToImage;
  final String content;

  const Article({
    required this.author,
    required this.title,
    required this.description,
    required this.url,
    required this.urlToImage,
    required this.content
  });

  factory Article.fromJson(Map<String, dynamic> json) {
    return Article(
      author: json['author'],
      title: json['title'],
      description: json['description'],
      url: json['url'],
      urlToImage: json['urlToImage'],
      content: json['content'],


    );
  }
}

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    const appTitle = 'NewApi Trial';

    return const MaterialApp(
      title: appTitle,
      home: MyHomePage(title: appTitle),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: FutureBuilder<List<Article>>(
        future: fetchArticles(http.Client()),
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            return Center(
              child: Text('An error has occurred! ${snapshot.error}'),
            );
          } else if (snapshot.hasData) {
            return ArticlesList(articles: snapshot.data!);
          } else {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      ),
    );
  }
}

class ArticlesList extends StatelessWidget {
  const ArticlesList({Key? key, required this.articles}) : super(key: key);

  final List<Article> articles;

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: articles.length,
      itemBuilder: (context, index) {
        return ClipRect(
          child: Column(
            children: [
              Image.network(articles[index].urlToImage),
              Text(articles[index].title)
            ],
          ),
        );
          //Image.network(Articles[index].thumbnailUrl);
      },
    );
  

} }

下面是运行代码后出现的错误

NoSuchMethodError: Class '_InternalLinkedHashMap'没有具有匹配参数的实例方法'cast'。接收者:_LinkedHashMap len:3 尝试调用:cast>() Founf: cast()=>Map

我们将不胜感激您的帮助

【问题讨论】:

    标签: json flutter flutter-futurebuilder


    【解决方案1】:

    main.dart

    import 'dart:convert';
    import 'package:flutter/material.dart';
    import 'package:http/http.dart' as http;
    import 'news_model.dart';
    
    void main() {
      runApp(MaterialApp(
        debugShowCheckedModeBanner: false,
        home: MyApp(),
      ));
    }
    
    // ignore: use_key_in_widget_constructors
    class MyApp extends StatefulWidget {
      @override
      _MyAppState createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      NewsModel? newsmodel;
      List<Articles>? articles;
    
      Future<List<Articles>?> fetchNews() async {
        final response = await http.get(Uri.parse(
            "https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=YourAPIKEYHere"));
        if (response.statusCode == 200) {
          newsmodel = NewsModel.fromJson(jsonDecode(response.body));
          setState(() {
            articles = newsmodel!.articles;
          });
          return articles;
        } else {
          articles = null;
        }
      }
    
      @override
      void initState() {
        fetchNews();
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: FutureBuilder<List<Articles>?>(
            future: fetchNews(),
            builder: (context, snapshot) {
              if (snapshot.hasError) {
                return Center(
                  child: Text('An error has occurred! ${snapshot.error}'),
                );
              } else if (snapshot.hasData) {
                return ArticlesList(articles: articles);
              } else {
                return const Center(
                  child: CircularProgressIndicator(),
                );
              }
            },
          ),
        );
      }
    }
    
    class ArticlesList extends StatelessWidget {
      const ArticlesList({Key? key, this.articles}) : super(key: key);
      final List<Articles>? articles;
    
      @override
      Widget build(BuildContext context) {
        return ListView.builder(
          itemCount: articles!.length,
          itemBuilder: (context, index) {
            return ClipRect(
              child: Column(
                children: [
                  Image.network(articles![index].urlToImage.toString()),
                  Text(articles![index].title.toString())
                ],
              ),
            );
            //Image.network(Articles[index].thumbnailUrl);
          },
        );
      }
    }
    

    news_model.dart

    class NewsModel {
      String? status;
      int? totalResults;
      List<Articles>? articles;
    
      NewsModel({this.status,this.totalResults,this.articles});
    
      NewsModel.fromJson(Map<String, dynamic> json) {
        status = json['status'];
        totalResults = json['totalResults'];
        if (json['articles'] != null) {
          articles = <Articles>[];
          json['articles'].forEach((v) {
            articles!.add(Articles.fromJson(v));
          });
        }
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = <String, dynamic>{};
        data['status'] = status;
        data['totalResults'] = totalResults;
        if (articles != null) {
          data['articles'] = articles!.map((v) => v.toJson()).toList();
        }
        return data;
      }
    }
    
    class Articles {
      Source? source;
      String? author;
      String? title;
      String? description;
      String? url;
      String? urlToImage;
      String? publishedAt;
      String? content;
    
      Articles(
          {this.source,
          this.author,
          this.title,
          this.description,
          this.url,
          this.urlToImage,
          this.publishedAt,
          this.content});
    
      Articles.fromJson(Map<String, dynamic> json) {
        source =
            json['source'] != null ? Source.fromJson(json['source']) : null;
        author = json['author'] ?? "Anonymous";
        title = json['title'] ?? "Information Not Available";
        description = json['description'] ?? "Description Not Available";
        url = json['url'] ?? "https://i.imgur.com/8UdKNS4.jpg";
        urlToImage = json['urlToImage'] ?? "https://i.imgur.com/8UdKNS4.jpg";
        publishedAt = json['publishedAt'] ?? "Date Unavailable";
        content = json['content'] ?? "Content Unavailable";
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = <String, dynamic>{};
        if (source != null) {
          data['source'] = source!.toJson();
        }
        data['author'] = author;
        data['title'] = title;
        data['description'] = description;
        data['url'] = url;
        data['urlToImage'] = urlToImage;
        data['publishedAt'] = publishedAt;
        data['content'] = content;
        return data;
      }
    }
    
    class Source {
      String? id;
      String? name;
    
      Source({this.id, this.name});
    
      Source.fromJson(Map<String, dynamic> json) {
        id = json['id'];
        name = json['name'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = <String, dynamic>{} ;
        data['id'] = id;
        data['name'] = name;
        return data;
      }
    }
    

    找到完整的项目here

    【讨论】:

      猜你喜欢
      • 2019-11-20
      • 2022-11-24
      • 2021-02-26
      • 2020-12-19
      • 2020-12-20
      • 1970-01-01
      • 2021-10-17
      • 2020-04-27
      相关资源
      最近更新 更多