JSON序列化问题:无法将参数类型'Tracks'分配给参数类型'Map <string,dynamic =“”>'

时间:2019-03-13 13:59:03

标签: flutter

我已经编写了一个自定义类型“ Tracks”,并且正在从JSON文件读取轨道,然后将其转换为<Tracks>的列表。

这是代码的一部分(在第四行引发错误):

Future loadTrackList() async {
    String content = await rootBundle.loadString('data/titles.json');
    List<Tracks> collection = json.decode(content);
    List<Tracks> _tracks = collection.map((json) => Tracks.fromJson(json)).toList();

    setState(() {
      tracks = _tracks;
    });   }

此外,这是我已序列化JSON的tracks.dart文件。

class Tracks{   final String title;   final String subtitle;

  Tracks(this.title, this.subtitle);


  Tracks.fromJson(Map<String, dynamic> json) :
      title = json['title'],
      subtitle = json['subtitle']; }

在我的原始使用场景中,我以这种方式使用以下曲目列表:

body: ListView.builder(
      itemCount: tracks.length,
      itemBuilder: (BuildContext context, int index) {
        var rnd = new Random();
        var totalUsers = rnd.nextInt(600);
        Tracks trackTitles = tracks[index];
        return PrimaryMail(
          iconData: OMIcons.supervisorAccount,
          title: trackTitles.title,
          count: "$totalUsers active",
          colors: Colors.lightBlueAccent,
        );
      },
    ),

现在,首先-在异步加载程序中的第一堆代码中,我得到了错误错误:The argument type 'Tracks' can't be assigned to the parameter type 'Map<String, dynamic>'.为行

List<Tracks> _tracks = collection.map((json) => Tracks.fromJson(json)).toList();

此外,当我在此处使用曲目时:

title: trackTitles.title, // inside listView builder

我收到错误消息(运行应用程序时,而不是之前):type '_InternalLinkedHashMap<String, dynamic is not a subtype of type 'tracks'

请求有关如何解决此问题的任何帮助。您可以find the important part of the whole code in this link很好地了解实施情况。

1 个答案:

答案 0 :(得分:0)

尝试一下

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:news_app/tracks.dart';

class TrackList extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _TrackListState();
}

class _TrackListState extends State<TrackList> {
  List<dynamic> tracks = List<dynamic>();

  Future loadTrackList() async {
    String content = await rootBundle.loadString('data/titles.json');
    var collection = json.decode(content);
    print(collection);
    List<dynamic> _tracks =
        collection.map((json) => Tracks.fromJson(json)).toList();

    setState(() {
      tracks = _tracks;
    });
  }

  void initState() {
    loadTrackList();
    super.initState();
  }

  @override
  Widget build(BuildContext context) => Scaffold(
        backgroundColor: Colors.white,
        body: Container(
          child: ListView.builder(
            itemCount: tracks.length,
            itemBuilder: (BuildContext context, int index) {
              Tracks item = tracks[index];
              return Text(item.title);
            },
          ),
        ),
      );
}