1

I am learning the Flutter framework and want to ask about the first example app from google tutorials. Namely, I wonder how this code really works.

Widget _buildSuggestions() {
    return new ListView.builder(
        padding: new EdgeInsets.all(6.0),
        itemBuilder: (_, int i) {
          if (i.isOdd)
            return new Divider(
              height: 1.0,
            );

          final int index = i ~/ 2;
          print(index);
          print('sug leng ${_suggestions.length}');
          if (index >= _suggestions.length) {
            _suggestions.addAll(generateWordPairs().take(10));
          }
          return _buildRow(_suggestions[index]);
        });
  }

How the words are really generated. Like when I inspect the index and the length of _suggestions it's saying that I've generated 20 words but the index is 14 when I slide down the index is moving up and at some point, the new words are added. How it detects when to add and when to stop counting the index? If someone can briefly explain to me this I would appreciate!! Thanks!

1 Answer 1

2

First off, ListView's itemBuilder is called lazily. Which means that ListView only request the widgets it needs. So when you scroll down, the index requested increases.

Then, the widget that instantiate ListView possess a _suggestions. Which is a list of suggestions.

The thing is, when ListView will try to access an index that is not available inside _suggestions, that code detect it and then insert another 10 suggestions to _suggestions before returning it.


While this code works ; don't use this logic if you want to have an infinite scroll behavior. This only work because it displays mocked data. But it won't work with datas coming from a server.

A more production ready approach would be to pass listview a ScrollController. And then listen that scrollcontroller to know when we reach the end of the current content.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for explanation! 😊

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.