Flutter

How to use ListView in Flutter?

ListView is very important widget in flutter. ListView is used to create the list of child widgets. But when we want to show construct the child widgets of demand then we use ListView.builder. This is the way to to generate dynamic contents. Instead of returning the static widgets in ListView we will use ListView.builder that will call multiple times and will return widgets recursively. We can also return different widget on each call. This is used to display long or infinite lists of data. For example the list of products, news messages and search results that are fetched form API.

Let’s see how to implement ListView.builder in Flutter.


Code

class FirstScreen extends StatefulWidget {
  const FirstScreen({Key? key}) : super(key: key);

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

class _FirstScreenState extends State<FirstScreen> {
  List<String> options = ['First Item', 'Second Item', 'Third Item'];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('List'),
      ),
      body: ListView.builder(
          itemCount: options.length,
          itemBuilder: (BuildContext ctx, int index) {
            return Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(options[index]),
            );
          }),
    );
  }
}

This is the basic ListView with 3 items. Similarly we can make a list of children on the base of dynamic  list. In the constructor of of ListView.builder you can see the two parameters that are required by this constructor. First one is ‘’itemcount’’, this is the value that tells how many times this callback function will in this item builder. As you can see that our list length is 3 and it display the items three times in list. And the second parameter is ‘’itemBuilder’’. This is the callback function that repeats itself and creates widgets again and again (how many times we have given in itemCount parameter).

Demo

One thought on “How to use ListView in Flutter?

  • Hi, this is a comment.
    To get started with moderating, editing, and deleting comments, please visit the Comments screen in the dashboard.
    Commenter avatars come from Gravatar.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *