JSON序列化问题:无法将参数类型“Tracks”分配给参数类型“Map” “

问题描述 投票:0回答:1

我写了一个自定义类型“Tracks”,我正在从JSON文件中读取轨道,然后转换为<Tracks>列表。

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

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

另外,这里是tracks.dart文件,我已经序列化了JSON。

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>'. for the line

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来了解实施情况。

flutter
1个回答
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);
            },
          ),
        ),
      );
}
© www.soinside.com 2019 - 2024. All rights reserved.