Brain2xml
Brain2xml

Reputation: 67

The method 'addAll' isn't defined for the class 'Future<List<Post>>'

trying create infinitive loading list

Future<List<Post>> fetchPost(page) async {
  final response =
  await http.get(Uri.parse('url?page=' + page.toString()));
  if (response.statusCode == 200) {
    final parsed = json.decode(response.body).cast<Map<String, dynamic>>();
    return parsed.map<Post>((json) => Post.fromMap(json)).toList();
  } else {
    throw Exception('Failed to load');
  }
}

and then in scroll listener

_scrollListener() {
    if (_scrollController.offset >=
        _scrollController.position.maxScrollExtent &&
        !_scrollController.position.outOfRange) {
      setState(() {
        print("comes to bottom");
        isLoading = true;

        if (isLoading) {
          print("RUNNING LOAD MORE");

          pageCount = pageCount + 1;
          var oldPost = fetchPost(pageCount);
          futurePost = futurePost.addAll(oldPost);
        }

      });
    }
  }

and get error The method 'addAll' isn't defined for the class 'Future<List>'

can't find information about it and in lot's of exaples this method used like default

Upvotes: 0

Views: 882

Answers (1)

Thomas
Thomas

Reputation: 181745

fetchPost is async, so it returns a Future, so you need to await its result. But this isn't allowed because the anonymous function passed to setState isn't async, and you shouldn't make it async either because all side effects are supposed to have happened as soon as that function returns.

Instead, refactor your code to do only the very minimal amount of work inside the setState callback:

_scrollListener() async {
    if (_scrollController.offset >=
        _scrollController.position.maxScrollExtent &&
        !_scrollController.position.outOfRange) {
      print("comes to bottom");
      isLoading = true;

      if (isLoading) {
        print("RUNNING LOAD MORE");

        pageCount = pageCount + 1;
        var oldPost = await fetchPost(pageCount);
        setState(() {
          futurePost = futurePost.addAll(oldPost);
        });
      }

    }
  }

Upvotes: 2

Related Questions