首页 > 解决方案 > 你如何打开一个列表进入列表 >>

问题描述

我开始学习 Flutter 是因为我想构建一个可以处理 API-Calls 的应用程序。但是现在我很沮丧,因为我想做一个无限的负载并且不让它工作。问题是,该方法需要 Future<List> 但我不知道如何将 API 的响应转换为 List

Future<List<Map>> _getServerData(int length) async{
  String api = data.url +length.toString();
  final res=
  await http.get("data.url");
  if (res.statusCode == 200) {
    List<dynamic> resp = jsonDecode(res.body);
    return resp;
  } else {
    throw Exception('Failed to load DATA');
  }
}

整个课程都来自 oodavid 的教程。但在他的教程中,他没有使用 API

Future<List<Map>> _getExampleServerData(int length) {
  return Future.delayed(Duration(seconds: 1), () {
    return List<Map>.generate(length, (int index) {
      return {
        "body": WordPair.random().asPascalCase,
        "avatar": 'https://api.adorable.io/avatars/60/${WordPair.random().asPascalCase}.png',
      };
    });
  });
}

他就是这样解决的下面是全班

import 'dart:async';
import 'dart:convert';
import 'package:Kontra/pages/articel_list.dart';
import 'package:http/http.dart' as http;
import 'package:Kontra/api/url.dart' as data;
import 'package:Kontra/api/articelsResponse.dart';

/// Example data as it might be returned by an external service
/// ...this is often a `Map` representing `JSON` or a `FireStore` document
Future<List<Map>> _getServerData(int length) async{
  String api = data.url +length.toString();
  final res=
  await http.get(data.url);
  if (res.statusCode == 200) {
    List<dynamic> resp = jsonDecode(res.body);
    return resp;
  } else {
    throw Exception('Failed to load DATA');
  }
}


/// PostModel has a constructor that can handle the `Map` data
/// ...from the server.
class PostModel {
  String sId;
  String title;
  String text;
  String author;
  String pictures;
  String link;
  int postId;
  String createdAt;
  PostModel({this.title, this.text, this.pictures, this.link, this.postId});
  factory PostModel.fromServerMap(Map<String, dynamic> json) {
    return PostModel(
      title: json['title'],
      text:  json['text'],
      pictures: json['pictures'],
      link: json['link'],
      postId: json['postId']
    );
  }
}

/// PostsModel controls a `Stream` of posts and handles
/// ...refreshing data and loading more posts
class PostsModel {
  int reload = 0;
  Stream<List<PostModel>> stream;
  bool hasMore;

  bool _isLoading;
  List<Map> _data;
  StreamController<List<Map>> _controller;

  PostsModel() {
    _data = List<Map>();
    _controller = StreamController<List<Map>>.broadcast();
    _isLoading = false;
    stream = _controller.stream.map((List<Map> postsData) {
      return postsData.map((Map postData) {
        return PostModel.fromServerMap(postData);
      }).toList();
    });
    hasMore = true;
    refresh();
  }

  Future<void> refresh() {
    return loadMore(clearCachedData: true);
  }

  Future<void> loadMore({bool clearCachedData = false}) {
    if (clearCachedData) {
      _data = List<Map>();
      hasMore = true;
    }
    if (_isLoading || !hasMore) {
      return Future.value();
    }
    _isLoading = true;
    return _getServerData(reload++).then((postsData) {
      _isLoading = false;
      _data.addAll(postsData);
      hasMore = (_data.length < 30);
      _controller.add(_data);
    });
  }
}

谢谢你们的帮助

标签: flutterdart

解决方案


尝试

return List<Map>.from(resp.whereType<Map>());

或者

return resp.whereType<Map>().toList();

或者

return resp.cast<Map>();

推荐阅读