Проблема с сериализацией JSON во флаттере - PullRequest
0 голосов
/ 05 апреля 2020

Я работаю с http-запросом, который приносит мне довольно сложный файл json, создаю класс модели с https://app.quicktype.io/, и когда я передаю json методу postdeUnCanalFrom Json () он выдает эту ошибку на меня, есть идеи, как ее решить?

Это ошибка: Возникла исключительная ситуация. _TypeError (type '(Dynami c) => PostdeUnCanal' не является подтипом типа '(String, Dynami c) => MapEntry' из 'Transform')

Это класс модели:

 import 'dart:convert';

List<PostdeUnCanal> postdeUnCanalFromJson(String str) => List<PostdeUnCanal>.from(json.decode(str).map((x) => PostdeUnCanal.fromMap(x)));

String postdeUnCanalToJson(List<PostdeUnCanal> data) => json.encode(List<dynamic>.from(data.map((x) => x.toMap())));

class PostdeUnCanal {
    String postId;
    String postTime;
    String postTypes;
    String postDescription;
    bool postShare;
    ReleaseContent releaseContent;
    Channel channel;
    String like;
    String unlike;
    String likeState;
    String status;

    PostdeUnCanal({
        this.postId,
        this.postTime,
        this.postTypes,
        this.postDescription,
        this.postShare,
        this.releaseContent,
        this.channel,
        this.like,
        this.unlike,
        this.likeState,
        this.status,
    });

    factory PostdeUnCanal.fromMap(Map<String, dynamic> json) => PostdeUnCanal(
        postId: json["postId"],
        postTime: json["postTime"],
        postTypes: json["postTypes"],
        postDescription: json["postDescription"],
        postShare: json["postShare"],
        releaseContent: ReleaseContent.fromMap(json["releaseContent"]),
        channel: Channel.fromMap(json["channel"]),
        like: json["like"],
        unlike: json["unlike"],
        likeState: json["likeState"],
        status: json["status"],
    );

    Map<String, dynamic> toMap() => {
        "postId": postId,
        "postTime": postTime,
        "postTypes": postTypes,
        "postDescription": postDescription,
        "postShare": postShare,
        "releaseContent": releaseContent.toMap(),
        "channel": channel.toMap(),
        "like": like,
        "unlike": unlike,
        "likeState": likeState,
        "status": status,
    };
}

class Channel {
    String channelId;
    String channelName;
    String channelCreator;
    int pendingNotifications;
    String status;

    Channel({
        this.channelId,
        this.channelName,
        this.channelCreator,
        this.pendingNotifications,
        this.status,
    });

    factory Channel.fromMap(Map<String, dynamic> json) => Channel(
        channelId: json["channelId"],
        channelName: json["channelName"],
        channelCreator: json["channelCreator"],
        pendingNotifications: json["pendingNotifications"],
        status: json["status"],
    );

    Map<String, dynamic> toMap() => {
        "channelId": channelId,
        "channelName": channelName,
        "channelCreator": channelCreator,
        "pendingNotifications": pendingNotifications,
        "status": status,
    };
}

class ReleaseContent {
    String title;
    String subtitle;
    String multimediaBase64;
    String date;
    String eventDateStart;
    String eventDateEnd;

    ReleaseContent({
        this.title,
        this.subtitle,
        this.multimediaBase64,
        this.date,
        this.eventDateStart,
        this.eventDateEnd,
    });

    factory ReleaseContent.fromMap(Map<String, dynamic> json) => ReleaseContent(
        title: json["title"],
        subtitle: json["subtitle"] == null ? null : json["subtitle"],
        multimediaBase64: json["multimediaBase64"],
        date: json["date"],
        eventDateStart: json["eventDateStart"],
        eventDateEnd: json["eventDateEnd"],
    );

    Map<String, dynamic> toMap() => {
        "title": title,
        "subtitle": subtitle == null ? null : subtitle,
        "multimediaBase64": multimediaBase64,
        "date": date,
        "eventDateStart": eventDateStart,
        "eventDateEnd": eventDateEnd,
    };
}

Это метод поставщика:

import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:pizarra_blanca/src/models/PostdeunCanal.dart';

import 'package:pizarra_blanca/src/models/post.dart';


class _PostProviderIndividual  {





Future<List<PostdeUnCanal>> obtenerFeed(String suscriptorId,String channelId ) async {
    String url = "https://pizarrablanca.org/api/feed/channel?channelId=$channelId&suscriptorId=$suscriptorId";
    print(url);
    var peticion = await http.get(url);
    var jsonData = (peticion.body); 
    var posts = postdeUnCanalFromJson(jsonData);
    return posts;



  }}

final postProviderIndividual = new _PostProviderIndividual();

Здесь я использую его в виджете:

   return  Scaffold(
            appBar: AppBar(

            title: Text("Desarrollo",textAlign:TextAlign.justify,),
            backgroundColor: Colors.deepPurpleAccent,
          ),
          body: FutureBuilder<List<PostdeUnCanal>>(
            initialData: [],
            future: postProviderIndividual.obtenerFeed(suscriptorId, channelId),
            builder: (BuildContext context, AsyncSnapshot<List<PostdeUnCanal>> snapshot) {
              if (snapshot.hasData) {
              return Container(
              child: ListView.builder(
              scrollDirection: Axis.vertical,
              shrinkWrap: true,
              physics: NeverScrollableScrollPhysics(),
              itemCount:snapshot.data.length,
              itemBuilder: (context, index) {
                var title         = snapshot.data[index].releaseContent.title;
                var channelName   = snapshot.data[index].channel.channelName;        
                var fecha         = snapshot.data[index].postTime;           
                var tipoContenido = snapshot.data[index].postTypes;           
                var contenido     = snapshot.data[index].releaseContent.multimediaBase64;
                var subtitle      = snapshot.data[index].releaseContent.subtitle;

                return Comunicado(title, channelName, fecha, tipoContenido, contenido,subtitle);
              },
            ));
            } else {
                return Center(child: Center(child: CircularProgressIndicator(),),);
              }
            }
              )
        );
      }
    }
...