Json 未处理的异常:类型'_内部链接dhashmap<;字符串,动态>';不是类型为';列表<;动态>';在类型转换中?

Json 未处理的异常:类型'_内部链接dhashmap<;字符串,动态>';不是类型为';列表<;动态>';在类型转换中?,json,flutter,dart,Json,Flutter,Dart,以下是回应 { "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 tow

以下是回应

{
"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']);
      }

}
类电影{
字符串标题;
字符串概述;
电影(
{this.title,this.overview});
factory Movies.fromJson(Map parsedJson){
返回电影(标题:parsedJson['title'],概述:parsedJson['overview']);
}
}

Future fetchMovies()异步{
var response=wait http.get(url);
var jsonData=jsonDecode(response.body)作为列表;
List movies=jsonData.map((e)=>movies.fromJson(e)).toList();
印刷品(电影长度);
返回电影;
}

我得到了这个错误(未处理的异常:类型'\u InternalLinkedHashMap'不是类型转换中类型'List'的子类型)

您尝试将jsonData转换为列表,但解码器说它是类型映射(您的响应也显示了它的类型映射)

Future fetchMovies()异步{
var response=wait http.get(url);
var jsonData=jsonDecode(response.body);
if(jsondataislist)//检查它是否是一个列表
返回List.from(jsonData.map(map)=>Movies.fromJson(map));
else if(jsonData是Map)//检查它是否是Map
return[Movies.fromJson(jsonData)];//返回长度为1的列表
}

您可以复制粘贴运行下面的完整代码
您可以使用
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);
List moviesFromJson(String str)=>
List.from(json.decode(str.map)((x)=>Movies.fromJson(x));
如果(response.statusCode==200){
从JSON(jsonString)返回moviesFromJson;
工作演示

完整代码

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,
                                      ),
                                    ),
                                  ],
                                ),
                              ));
                        });
                  }
              }
            }));
  }
}
导入“包装:颤振/材料.省道”;
将“package:http/http.dart”导入为http;
导入“dart:convert”;
List moviesFromJson(字符串str)=>
List.from(json.decode(str.map)((x)=>Movies.fromJson(x));
字符串moviesToJson(列表数据)=>
encode(List.from(data.map((x)=>x.toJson());
班级电影{
电影({
这是一个概述,
这个名字,
});
字符串概述;
字符串标题;
factory Movies.fromJson(映射json)=>Movies(
概述:json[“概述”],
标题:json[“标题”],
);
映射到JSON()=>{
“概述”:概述,
“头衔”:头衔,
};
}
void main(){
runApp(MyApp());
}
类MyApp扩展了无状态小部件{
@凌驾
小部件构建(构建上下文){
返回材料PP(
标题:“颤振演示”,
主题:主题数据(
主样本:颜色。蓝色,
视觉密度:视觉密度。自适应平台密度,
),
主页:MyHomePage(标题:“颤振演示主页”),
);
}
}
类MyHomePage扩展StatefulWidget{
MyHomePage({Key,this.title}):超级(Key:Key);
最后的字符串标题;
@凌驾
_MyHomePageState createState()=>\u MyHomePageState();
}
类_MyHomePageState扩展状态{
int _计数器=0;
未来,未来;;
Future fetchMovies()异步{
字符串jsonString='''
[{
“概述”:“随着地下“搏击俱乐部”在每个城镇的形成,直到一个怪人挡道并点燃一个失控的螺旋走向遗忘”,
“头衔”:“搏击俱乐部”
},
{
“概述”:“测试概述”,
“标题”:“测试标题”
}
]
''';
var response=http.response(jsonString,200);
如果(response.statusCode==200){
从JSON(jsonString)返回moviesFromJson;
}否则{
打印(响应状态码);
}
}
@凌驾
void initState(){
_future=fetchMovies();
super.initState();
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
标题:文本(widget.title),
),
正文:未来建设者(
未来:未来,
生成器:(上下文,异步快照){
交换机(快照.连接状态){
案例连接状态。无:
返回文本(“无”);
案例连接状态。正在等待:
返回中心(子项:CircularProgressIndicator());
案例连接状态.active:
返回文本(“”);
案例连接状态。完成:
if(snapshot.hasError){
返回文本(
“${snapshot.error}”,
样式:TextStyle(颜色:Colors.red),
);
}否则{
返回ListView.builder(
itemCount:snapshot.data.length,
itemBuilder:(上下文,索引){
回程卡(
标高:6.0,
孩子:填充(
填充:仅限常量边设置(
排名:6.0,
底部:6.0,
左:8.0,
右:8.0),
孩子:排(
crossAxisAlignment:crossAxisAlignment.start,
儿童:[
文本(快照.数据[索引].标题),
垫片(),
扩大(
子:文本(
快照。数据[索引]。概述,
),
),
],
),
));
});
}
}
}));
}
}

看看他的答案就知道了

[
    {
       "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"
    }
 ]
模型

//要解析此JSON数据,请执行以下操作
//
//最终电影=moviesFromJson(jsonString);
导入“dart:convert”;
List moviesFromJson(String str)=>List.from(json.decode(str.map)(x)=>Movies.fromJson(x));
字符串moviesToJso
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,
                                      ),
                                    ),
                                  ],
                                ),
                              ));
                        });
                  }
              }
            }));
  }
}
[
    {
       "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,
    };
}

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),
                    ));
                  }),
            ),
    );
  }
}