颤振从json中获取数据“字符串不是Iterable<dynamic>的子类型”

时间:2021-02-16 14:12:07

标签: flutter fetch-api

我正在尝试从我的服务器获取数据,但我遇到了类型错误。我已经遵循了几个教程并在这里回答但没有成功。

这是我遇到错误的课程:

class BeachList{
  final List<Beach> beach;

  BeachList({this.beach});

  factory BeachList.fromJson(List<dynamic>parsedJson){
    List<Beach> beach= List<Beach>();
    beach=parsedJson.map((i)=>Beach.fromJson(i)).toList();

    return BeachList(
      beach: beach
      );
  }
}

class Beach {
  final int id; //id plage
  final String beachName; // nom de la plage
  final String commune;
  final String codedep;
  final int eval; // note d'évalutation sur la présence de sargasses
  final List<String> imageUrl;
  final DateTime dateMaj; //date de mise à jour
  final List<double> xyBeach;
  final String meteoval;
  final int sarguasseval;
  final List<String> listofcomment;


  Beach({this.id,  
      this.beachName,
      this.commune,
      this.codedep,
      this.eval,
      this.imageUrl,
      this.dateMaj,
      this.xyBeach,
      this.meteoval,
      this.sarguasseval,
      this.listofcomment});

  // la partie qui suit est rajoutée
  factory Beach.fromJson(Map<String, dynamic> json){
    return Beach(
      id: json['id'] as int,
      beachName: json['nompl'] as String,
      commune: json['commune'] as String,
      codedep: json['codedep'] as String,
      eval: json['eval'] as int,
      imageUrl: parseImage(json['imageurl']),
      dateMaj: json['datemaj'] as DateTime,
      xyBeach: parseCoord(json['coordpl']),
      meteoval: json[''] as String,
      sarguasseval: json['sargasse'] as int,
      listofcomment: parsecomment(json['comment']) 
    );
  }
  static List<String> parseImage(imageJson){
    List<String> imageUrl=List<String>.from(imageJson);// ERROR : "string is not a subtype of Iterable<dynamic>"
    return imageUrl;
  }

  static List<double> parseCoord(coordJson){
     List<double>xyBeach=List<double>.from(coordJson);
     return xyBeach;
  }

    static List<String> parsecomment(comJson){
    List<String> listofcomment=List<String>.from(comJson);
    return listofcomment;
  }
}

JSON 数据:

[0{
"id":10,
"nompl":"Plage des Surfeurs",
"commune":"La Trinité",
"codedep":"MQ",
"coordpl":"[0:1]={14.76989155,-60.8994565957988}",
"imageurl":"[0:0]={https:\/\/www.aircaraibes.com\/sites\/default\/files\/img_p_text_image\/plus-belles-plages-de-martinique.jpg}",
"sargasse":"1",
"datemaj":null,
"meteoval":null,
"temperature":null,
"listofcomment":null,
"datepost":null}...]

pb 似乎不是来自 Beachlist,我已经评论了这部分代码,并在我将来用 Beach classe 替换等,但后来我遇到了类似的错误:string 不是 List 的子类型:/

我用这个 Future 调用 Json 数据:

Future<BeachList> fetchBeach() async {
  final response =
      await http.get("http://URLSERVER/mq_beach.php");
  if (response.statusCode == 200) {
    var parsed = jsonDecode(response.body);
    BeachList beach = BeachList.fromJson(parsed);
    print(beach.beaches[0].beachName);
    return beach;
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load data');
  }
}

初始化为initstate:

 Future<BeachList> parsedjson;
  @override
  void initState() {
    super.initState();
    parsedjson = fetchBeach();
  }

并显示数据:

 Scaffold(
        body: Column(
            children: BeachList.fromJson(parsedjson)//error
                .beaches
                .map((beach) => Text(beach.beachName))
                .toList()));

我收到错误:无法将参数类型“未来”分配给参数类型“列表”

1 个答案:

答案 0 :(得分:0)

您的 parseImageparseCoord 完全关闭。

关于您的数据的 JSON 格式,我没有足够的信息。但是,我希望以下内容能让您走上正确的道路:

static List<String> parseImage(imageJson) {
  final regExp = RegExp(r"{(.*?)}");
  return regExp.allMatches(imageJson).map((match) => match.group(1)).toList();
}

static List<double> parseCoord(coordJson) {
  final regExp = RegExp(r"{(.*?)}");
  return regExp
    .allMatches(coordJson)
    .map((match) => match.group(1))
    .toList()
    .first
    .split(',')
    .map(double.parse)
    .toList();
}

我只是在 {...} 之间获取数据。不过不确定它是否正确。

带有虚假数据的样本的完整源代码

import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:faker/faker.dart';

void main() {
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      home: HomePage(),
    ),
  );
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: BeachList.fromJson(data)
            .beaches
            .map((beach) => Text(beach.beachName))
            .toList(),
      ),
    );
  }
}

class BeachList {
  final List<Beach> beaches;

  BeachList({this.beaches});

  factory BeachList.fromJson(List<dynamic> parsedJson) => BeachList(
      beaches: parsedJson.map((beach) => Beach.fromJson(beach)).toList());
}

class Beach {
  final int id; //id plage
  final String beachName; // nom de la plage
  final String commune;
  final String codedep;
  final int eval; // note d'évalutation sur la présence de sargasses
  final List<String> imageUrl;
  final DateTime dateMaj; //date de mise à jour
  final List<double> xyBeach;
  final String meteoval;
  final String sarguasseval;
  final List<String> listofcomment;

  Beach(
      {this.id,
      this.beachName,
      this.commune,
      this.codedep,
      this.eval,
      this.imageUrl,
      this.dateMaj,
      this.xyBeach,
      this.meteoval,
      this.sarguasseval,
      this.listofcomment});

  // la partie qui suit est rajoutée
  factory Beach.fromJson(Map<String, dynamic> json) {
    return Beach(
        id: json['id'] as int,
        beachName: json['nompl'] as String,
        commune: json['commune'] as String,
        codedep: json['codedep'] as String,
        eval: json['eval'] as int,
        imageUrl: parseImage(json['imageurl']),
        dateMaj: json['datemaj'] as DateTime,
        xyBeach: parseCoord(json['coordpl']),
        meteoval: json[''] as String,
        sarguasseval: json['sargasse'] as int,
        listofcomment: parsecomment(json['comment']));
  }
  static List<String> parseImage(imageJson) {
    final regExp = RegExp(r"{(.*?)}");
    return regExp.allMatches(imageJson).map((match) => match.group(1)).toList();
  }

  static List<double> parseCoord(coordJson) {
    final regExp = RegExp(r"{(.*?)}");
    return regExp
        .allMatches(coordJson)
        .map((match) => match.group(1))
        .toList()
        .first
        .split(',')
        .map(double.parse)
        .toList();
  }

  static List<String> parsecomment(comJson) {
    List<String> listofcomment = List<String>.from(comJson ?? []);
    return listofcomment;
  }
}

final random = math.Random();
final faker = Faker();

final data = List.generate(
  10,
  (index) => {
    'id': index,
    'nompl': faker.person.lastName(),
    'commune': faker.address.city(),
    'codedep': faker.randomGenerator.string(6, min: 6),
    'eval': random.nextInt(10),
    // "imageurl":"[0:0]={https:\/\/www.aircaraibes.com\/sites\/default\/files\/img_p_text_image\/plus-belles-plages-de-martinique.jpg}",
    'imageurl': '[0:0]={${faker.image.image()}},[0:1]={${faker.image.image()}}',
    'datemaj': faker.date.dateTime(),
    //"coordpl":"[0:1]={14.76989155,-60.8994565957988}",
    'coordpl':
        '[0:1]={${random.nextDouble() * 180 - 90},${random.nextDouble() * 360 - 180}}',
    //meteoval: json[''] as String,
    'sargasse': random.nextInt(10),
    'comment': List.generate(random.nextInt(3), (_) => faker.lorem.sentence()),
  },
);