当前位置: 首页 > 知识库问答 >
问题:

未处理的异常:类型“\u InternalLinkedHashMap”不是类型转换中“List”类型的子类型?

白光耀
2023-03-14

以下是回应

{
"overview": "A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground "fight clubs" forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.",
"title": "Fight Club",
}

模型

class Movies {
  String title;
  String overview;
  

  Movies(
      {this.title , this.overview});

      factory Movies.fromJson(Map <String, dynamic> parsedJson){
        return Movies(title: parsedJson['title'] , overview: parsedJson['overview']);
      }

}

  Future <List<Movies>> fetchMovies () async {
    var response = await http.get(url);
    var jsonData = jsonDecode(response.body) as List ;
    List<Movies> movies = jsonData.map((e) => Movies.fromJson(e)).toList();
    
    print(movies.length);
    return movies;

  }

我收到此错误(未处理的异常:键入“\u InternalLinkedHashMap

共有3个答案

曾德水
2023-03-14

看看他的回答

[
    {
       "overview":"A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground \"fight clubs\" forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.",
       "title":"Fight Club"
    },
    {
       "overview":"A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground fight clubs forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.",
       "title":"second Club"
    }
 ]

模型

// To parse this JSON data, do
//
//     final movies = moviesFromJson(jsonString);

import 'dart:convert';

List<Movies> moviesFromJson(String str) => List<Movies>.from(json.decode(str).map((x) => Movies.fromJson(x)));

String moviesToJson(List<Movies> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Movies {
    Movies({
        this.overview,
        this.title,
    });

    String overview;
    String title;

    factory Movies.fromJson(Map<String, dynamic> json) => Movies(
        overview: json["overview"],
        title: json["title"],
    );

    Map<String, dynamic> toJson() => {
        "overview": overview,
        "title": title,
    };
}

UI页面:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:json_parsing_example/models.dart';

// To parse this JSON data, do
//
//     final user = userFromJson(jsonString);

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Users'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool _isLoading = false;
  List<Movies> dataList = List();
  Future<String> loadFromAssets() async {
    return await rootBundle.loadString('json/parse.json');
  }

  @override
  void initState() {
    super.initState();
    getData();
  }

  getData() async {
    setState(() {
      _isLoading = true;
    });
    String jsonString = await loadFromAssets();
    final movies = moviesFromJson(jsonString);

    dataList = movies;

    setState(() {
      _isLoading = false;
    });
  }
    // In your case you just check out this code check out the model class
  /* Future <List<Movies>> fetchMovies () async {
    var response = await http.get(url);
    return moviesFromJson(response.body);

  } */

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: _isLoading
          ? Center(
              child: CircularProgressIndicator(),
            )
          : Container(
              child: ListView.builder(
                  itemCount: dataList.length,
                  shrinkWrap: true,
                  itemBuilder: (context, i) {
                    return Card(
                        child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(dataList[i].overview),
                    ));
                  }),
            ),
    );
  }
}

要告诉你的是概述的值有双引号,这就是为什么可能会有一些解析问题,只要检查代码,让我知道它是否工作。

庄浩言
2023-03-14

您可以在下面复制粘贴运行完整代码
您可以使用moviesFromJson并使用FutureBuilder
代码片段显示

List<Movies> moviesFromJson(String str) =>
    List<Movies>.from(json.decode(str).map((x) => Movies.fromJson(x)));
    
if (response.statusCode == 200) {
      return moviesFromJson(jsonString);

工作演示

完整代码

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

List<Movies> moviesFromJson(String str) =>
    List<Movies>.from(json.decode(str).map((x) => Movies.fromJson(x)));

String moviesToJson(List<Movies> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Movies {
  Movies({
    this.overview,
    this.title,
  });

  String overview;
  String title;

  factory Movies.fromJson(Map<String, dynamic> json) => Movies(
        overview: json["overview"],
        title: json["title"],
      );

  Map<String, dynamic> toJson() => {
        "overview": overview,
        "title": title,
      };
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  Future<List<Movies>> _future;

  Future<List<Movies>> fetchMovies() async {
    String jsonString = '''
    [{
"overview" : "with underground \\"fight clubs\\" forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion",
"title" : "Fight Club"
},
{
"overview" : "test overview",
"title" : "test title"
}
]
    ''';

    var response = http.Response(jsonString, 200);

    if (response.statusCode == 200) {
      return moviesFromJson(jsonString);
    } else {
      print(response.statusCode);
    }
  }

  @override
  void initState() {
    _future = fetchMovies();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: FutureBuilder(
            future: _future,
            builder: (context, AsyncSnapshot<List<Movies>> snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                  return Text('none');
                case ConnectionState.waiting:
                  return Center(child: CircularProgressIndicator());
                case ConnectionState.active:
                  return Text('');
                case ConnectionState.done:
                  if (snapshot.hasError) {
                    return Text(
                      '${snapshot.error}',
                      style: TextStyle(color: Colors.red),
                    );
                  } else {
                    return ListView.builder(
                        itemCount: snapshot.data.length,
                        itemBuilder: (context, index) {
                          return Card(
                              elevation: 6.0,
                              child: Padding(
                                padding: const EdgeInsets.only(
                                    top: 6.0,
                                    bottom: 6.0,
                                    left: 8.0,
                                    right: 8.0),
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text(snapshot.data[index].title),
                                    Spacer(),
                                    Expanded(
                                      child: Text(
                                        snapshot.data[index].overview,
                                      ),
                                    ),
                                  ],
                                ),
                              ));
                        });
                  }
              }
            }));
  }
}
方通
2023-03-14

您试图将jsonData强制转换为List,但解码器说它是Map类型(您的响应也显示了它的Map类型)

Future <List<Movies>> fetchMovies () async {
  var response = await http.get(url);
  var jsonData = jsonDecode(response.body);
  if(jsonData is List) //check if it's a List
    return List<Movies>.from(jsonData.map(map) => Movies.fromJson(map));
  else if(jsonData is Map) //check if it's a Map
    return [Movies.fromJson(jsonData)]; //return a List of length 1

}
 类似资料:
  • 我一直在我的颤振应用程序中使用sembast,我在我的类设备中包含我的类温度列表时遇到了问题。我已经包括以下两个类。 我得到未处理的异常:键入“ImmutableMap” 这种方法似乎被用于其他问题的解决方案,这些问题似乎与我的问题几乎相同,所以我不确定这里有什么问题,以及我尝试过的其他解决方案。

  • 我正在开发我的flutter应用程序的身份验证。请帮我解决这个问题。我无法识别返回这样一个错误的问题,声明未处理异常:类型列表不是类型字符串的子类型。 以下是登录屏幕的代码: 执行登录的上述代码部分: 错误

  • 更新:感谢@Rjulcaa回答我的地图现在是一个列表,但是列表没有显示在用户界面上。我转过来,我需要用FutureBuilder来处理未来,所以如果有人面临这个问题,记得在你的用户界面主体中添加一个FutureBuilder,并在构建器上返回你想要显示的小部件。 我正在制作一个todo列表教程,我正在尝试添加JSON上的编码功能,我的todoList将其保存在SharedReferences上,当

  • 我对使用颤振和特定于平台的代码非常陌生,所以如果这是一个愚蠢的问题,请原谅我。我正在使用一个事件通道将数据从android端返回到Flatter。我正在返回一份清单 但是,当我试图添加它时,它给出了一个异常,“未处理的异常:类型'列表'不是类型'列表'的子类型 这是我要将贴图对象添加到的列表。 列表 这是我的添加代码。忽略print语句。 我尝试过像cast或from这样的方法,但它对我不起作用,

  • 我正在解码一个响应体,我得到了错误: 我在Udemy上学习颤振教程时,正在尝试使用API。教程说要使用https://javiercbk.github.io/json_to_dart/将JSON转换为Dart。我把JSON从https://www.openbrewerydb.org/并将其转换为Dart,但我遇到的问题是,当我尝试解码API时,我得到了未处理的错误异常:“List”类型不是“Map