如何在飞镖颤振上获取贴图?

时间:2020-10-20 09:24:39

标签: flutter dart

我有这种错误, type List<dynamic> is not a subtype of type Map<String, dynamic>,我已经搜索了许多问题,但仍然无法理解该错误的目的。这是我的api代码

import 'dart:convert';

import 'package:learn_how_to_fetch/announcement.dart';
import 'package:requests/requests.dart';

Future<Announcement> fetchAnnouncement() async {
Map<String, String> headers = {
  'Content-Type': 'application/json;charset=UTF-8',
  'Charset': 'utf-8'
};
var response = await Requests.get('http://172.16.54.2:5000/api/announcelist',
  verify: false, headers: headers);
 response.raiseForStatus();
 // final jsonTried = json.decode(response.content()) as List;
 // print(json);
 if (response.statusCode == 200) {
 final jsonResponse = json.decode(response.content());
 // print(jsonResponse
 List<Announcement> anonList = []
 Announcement anonResponse = Announcement.fromJson(jsonResponse);
 print(anonResponse.id);
 return anonResponse;
 } else {
 // If the server did not return a 200 OK response,
 // then throw an exception.
  throw Exception('Failed to load album');
  } 
 }  

这是我的公告类方法

class Announcement {
int id;
String title;
String image;
String content;
String text;
int active;

 Announcement(
  {this.id, this.title, this.image, this.content, this.text, this.active});

Announcement.fromJson(Map<String, dynamic> json) {
  id = json['id'];
  title = json['title'];
  image = json['image'];
  content = json['content'];
  text = json['text'];
  active = json['active'];
}

Map<String, dynamic> toJson() {
  final Map<String, dynamic> data = new Map<String, dynamic>();
  data['id'] = this.id;
  data['title'] = this.title;
  data['image'] = this.image;
  data['content'] = this.content;
  data['text'] = this.text;
  data['active'] = this.active;
  return data;
}
}

这是我使用的main.dart

import 'package:flutter/material.dart';
import 'package:learn_how_to_fetch/announcement.dart';
import 'package:learn_how_to_fetch/api.dart';

void main() => runApp(MyApp());

 class MyApp extends StatefulWidget {
 MyApp({Key key}) : super(key: key);

 @override
 _MyAppState createState() => _MyAppState();
 }

 class _MyAppState extends State<MyApp> {
 Future<Announcement> futureAnnouncement;

 @override 
 void initState() {
  super.initState();
  futureAnnouncement = fetchAnnouncement();
 }

 @override
 Widget build(BuildContext context) {
return MaterialApp(
  title: 'Fetch Data Example',
  theme: ThemeData(
    primarySwatch: Colors.blue,
  ),
  home: Scaffold(
    appBar: AppBar(
      title: Text('Fetch Data Example'),
    ),
    body: Center(
      child: FutureBuilder<Announcement>(
        future: futureAnnouncement,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return Text(snapshot.data.title);
          } else if (snapshot.hasError) {
            return Text("${snapshot.error}");
          }

          // By default, show a loading spinner.
          return CircularProgressIndicator();
        },
      ),
    ),
  ),
);
}
}

这是服务器的响应

  [{
    "id": 57,
    "title": "Title",
    "image": "image/specialitem/SPI1454050237.jpg",
    "content": "Something",
    "text": "<Content>",
    "active": 0
 },
{...}]

但是问题是我似乎无法理解该错误。我曾经尝试过此链接this problem,但仍然无法解决问题

2 个答案:

答案 0 :(得分:2)

问题是,您从服务器获取JSON列表。

在JSON列表上使用json.decode()返回一个列表。

但是您的代码希望jsonResponse是一个Map。

答案 1 :(得分:0)

您应该首先在列表中获得服务器响应,然后将所有元素转换为自定义类,即公告。尝试以下代码:

Future<Announcement> fetchAnnouncement() async {
  Map<String, String> headers = {
    'Content-Type': 'application/json;charset=UTF-8',
    'Charset': 'utf-8'
  };
  var response = await Requests.get('http://172.16.54.2:5000/api/announcelist',
      verify: false, headers: headers);
  response.raiseForStatus();
  // final jsonTried = json.decode(response.content()) as List;
  // print(json);
  if (response.statusCode == 200) {
    final jsonResponse = json.decode(response.content());
    // print(jsonResponse
    List<dynamic> anonList = jsonResponse;
    List<Announcement> anonResponse = [];
    for (int i = 0; i < anonList.length; i++) {
      anonResponse.add(Announcement.fromJson(anonList[i]));
    }
    print(anonResponse);
    return anonResponse[0];
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}