_TypeError (type '(Dynami c) => Article' не является подтипом типа '(String, Dynami c) => MapEntry 'из' преобразования ') - PullRequest
0 голосов
/ 04 августа 2020

Ошибка обычно возникает, когда я прокручиваю список сообщений до конца.

Вот код для получения сообщений из Word press api

     Future<List<dynamic>> fetchLatestArticles(int page) async {
    try {
      var response = await http.get(
          '$WORDPRESS_URL/wp-json/wp/v2/posts/?page=$page&per_page=10&_fields=id,date,title,content,custom,link');
      if (this.mounted) {
        if (response.statusCode == 200) {
          setState(() {
            latestArticles.addAll(json
                .decode(response.body)
                .map((m) => Article.fromJson(m))
                .toList());

            if (latestArticles.length % 10 != 0) {
              _infiniteStop = true;
            } else {
              _infiniteStop = false;
            }
          });
          return latestArticles;
        }
        setState(() {
          _infiniteStop = true;
        });
      }
    } on SocketException {
      throw 'No Internet connection';
    }
    return latestArticles;
  }

вот пример ответа на вызов api

[
    {
        "id": "",
        "date": "",
        "link": " ",
        "title": {
            "rendered": " "
        },
        "content": {
            "rendered": " ",
            "protected": false
        }
    },
    {
        "id": "",
        "date": " ",
        "link": " ",
        "title": {
            "rendered": " "
        },
        "content": {
            "rendered": " ",
            "protected": false
        }
    }
   
]

1 Ответ

0 голосов
/ 04 августа 2020

Вы можете скопировать и вставить полный код ниже
Вы можете использовать latestArticles.addAll(articleFromJson(response.body));

фрагмент кода

List<Article> articleFromJson(String str) => List<Article>.from(json.decode(str).map((x) => Article.fromJson(x)));
...
if (this.mounted) {
        if (response.statusCode == 200) {
          setState(() {
            latestArticles.addAll(articleFromJson(response.body));

рабочая демонстрация

введите описание изображения здесь

полный код

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

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

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

class Article {
  Article({
    this.id,
    this.date,
    this.link,
    this.title,
    this.content,
  });

  String id;
  String date;
  String link;
  Title title;
  Content content;

  factory Article.fromJson(Map<String, dynamic> json) => Article(
        id: json["id"],
        date: json["date"],
        link: json["link"],
        title: Title.fromJson(json["title"]),
        content: Content.fromJson(json["content"]),
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "date": date,
        "link": link,
        "title": title.toJson(),
        "content": content.toJson(),
      };
}

class Content {
  Content({
    this.rendered,
    this.protected,
  });

  String rendered;
  bool protected;

  factory Content.fromJson(Map<String, dynamic> json) => Content(
        rendered: json["rendered"],
        protected: json["protected"],
      );

  Map<String, dynamic> toJson() => {
        "rendered": rendered,
        "protected": protected,
      };
}

class Title {
  Title({
    this.rendered,
  });

  String rendered;

  factory Title.fromJson(Map<String, dynamic> json) => Title(
        rendered: json["rendered"],
      );

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

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;
  List<Article> latestArticles = [];
  bool _infiniteStop;
  Function _future;

  Future<List<Article>> fetchLatestArticles(int page) async {
    try {
      /*var response = await http.get(
          '$WORDPRESS_URL/wp-json/wp/v2/posts/?page=$page&per_page=10&_fields=id,date,title,content,custom,link');*/
      String jsonString = '''
      [
    {
        "id": "123",
        "date": "",
        "link": " ",
        "title": {
            "rendered": "abc"
        },
        "content": {
            "rendered": " ",
            "protected": false
        }
    },
    {
        "id": "456",
        "date": " ",
        "link": " ",
        "title": {
            "rendered": "def"
        },
        "content": {
            "rendered": " ",
            "protected": false
        }
    }
   
]
      ''';
      http.Response response = http.Response(jsonString, 200);
      if (this.mounted) {
        if (response.statusCode == 200) {
          setState(() {
            latestArticles.addAll(articleFromJson(response.body));

            if (latestArticles.length % 10 != 0) {
              _infiniteStop = true;
            } else {
              _infiniteStop = false;
            }
          });
          return latestArticles;
        }
        setState(() {
          _infiniteStop = true;
        });
      }
    } on SocketException {
      throw 'No Internet connection';
    }
    return latestArticles;
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: FutureBuilder(
            future: _future(1),
            builder: (context, AsyncSnapshot<List<Article>> 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.rendered),
                                    Spacer(),
                                    Text(
                                      snapshot.data[index].id,
                                    ),
                                  ],
                                ),
                              ));
                        });
                  }
              }
            }));
  }
}
            
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...