AppDividend
Latest Code Tutorials

Flutter ListView Example | Displaying Dynamic Contents Tutorial

0 245

Get real time updates directly on you device, subscribe now.

In this tutorial, we will see Flutter ListView Example | Displaying Dynamic Contents. Flutter is the mobile App SDK by Google which helps in creating modern mobile apps for iOS and Android using the single code base. It’s the new entrant in the cross-platform mobile application development, and unlike other frameworks like React Native, it doesn’t use JavaScript but Dart as the Programming Language.

If you don’t know how to install Flutter, then check out my How To Install Flutter article.  In the real-world apps, dynamic contents are always there and, it is fetched from a backend. So, we need to display those contents in such a way that it does not annoy the user while scrolling down the page.

In this tutorial, we will create a button widget, and when the button is pressed, it will add an item to the List and display that List on the mobile screen. So, when the button is pressed, the state of the widget will change, and the UI will be re-rendered, and we will see the products list inside the mobile screen.

If the length of the item will be increased and reach the limit where we need to scroll down the page, we need to display the scrollbar so that user can quickly scroll down the page. If we do not use ListView, then it will throw a warning in yellow line to indicate that we need to use some widget to show the proper user content and that is why we will use the ListView widget of flutter.

Flutter ListView Example

The standard ListView constructor works well for small lists. If we want to work with lists that contain the large number of items, it’s best to use the ListView.builder constructor.

The main difference between ListView and ListView.builder is that the default ListView constructor requires us to create all items at once whereas the ListView.builder constructor will create items as they are scrolled onto the screen like on demand.

We will use ListView.builder constructor for displaying the items. Let us create a new app in the Visual Studio Code.

Step 1: Create a new flutter project

Go to the VSCode and hit the shortcut keys: cmd + shift + p and type the flutter and it will show to create a new project option, and it creates a new flutter project in your specified folder.

Also, create one folder called assets in the root of the project, we will copy one image to that folder to display inside the Flutter app.

Now, we are going to show an image from the local folder. So, we need to add an image inside pubspec.yaml file.

Add the following line of code inside the pubspec.yaml file.

assets:
    - assets/macbook.jpg

There is already commented line by default by flutter; you need to uncomment it and replace the first line with the assets/your image file with extension.

If you still do not know how to display the image inside the Flutter app then check out How To Display Image in Flutter.

Step 2: Write the Stateful Widget

Now, if you do not know how to write the Stateful Widget in Flutter then check out my this article.

Write the following code inside the main.dart file.

// main.dart

import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  List<String> _products = ['Laptop'];
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(primarySwatch: Colors.deepPurple),
      home: Scaffold(
        appBar: AppBar(title: Text('Long List App')),
        body: Column(children: [
          Container(
              margin: EdgeInsets.all(10.0),
              child: RaisedButton(
                  color: Theme.of(context).primaryColor,
                  splashColor: Colors.blueGrey,
                  textColor: Colors.white,
                  onPressed: () {
                    setState(() {
                      _products.add('Macbook');
                    });
                  },
                  child: Text('Add Laptops'))),
          Column(
              children: _products
                  .map((element) => Card(
                        child: Column(
                          children: <Widget>[
                            Image.asset('assets/macbook.jpg'),
                            Text(element,
                                style: TextStyle(color: Colors.deepPurple))
                          ],
                        ),
                      ))
                  .toList()),
        ]),
      ),
    );
  }
}

First, we have created a stateful widget and then set up the theme for the flutter application. Then we have taken one Raised Button, and when the user presses the button, we will add the laptop to the array and display that with the help Card Widget.

We are displaying the two items.

  1. Image
  2. Text

Now, save a file and go to the terminal and type the following command.

flutter run -d all

Make sure; you have opened the iOS Simulator and Android Emulator. After the compilation process, you will see something like this.

Flutter ListView Example | Displaying Dynamic Contents Tutorial

 

Related Posts
1 of 3

Now, click on the Add Laptops button and you will see we can see the second item added into an array.

Now, try to add two or more items, you will see the yellow warning like below.

 

Displaying Dynamic Contents Tutorial

To resolve this problem, we need a ListView.builder() Widget and let us that widget.

Step 3: Add ListView.builder() widget

Let us understand the ListView.builder() widget.

ListView.builder constructor

It creates the scrollable, linear array of widgets that are created on demand.

ListView.builder() constructor is appropriate for list views with ahe large (or infinite) number of children because the builder is called only for those children that are visible.

Providing the non-null itemCount improves the ability of the ListView to estimate the maximum scroll extent.

The itemBuilder callback will be called only with indices greater than or equal to zero and less than itemCount.

Next step is, we will split our codebase into two files.

  1. products.dart
  2. main.dart

The products.dart file only responsible for displaying the items in card widget with the help of ListView.builder constructor widget.

Create one file called products.dart inside the lib folder and add the following code.

// products.dart

import 'package:flutter/material.dart';

class Products extends StatelessWidget {
  final List<String> products;
  Products(this.products);

  Widget _buildProductItem(BuildContext context, int index) {
    return Card(
      child: Column(
        children: <Widget>[
          Image.asset('assets/macbook.jpg'),
          Text(products[index], style: TextStyle(color: Colors.deepPurple))
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemBuilder: _buildProductItem,
      itemCount: products.length,
    );
  }
}

So, this is the Products class, which has one method called _buildProductItem. This function returns the ListView.builder widget.

ListView.builder widget takes two arguments. One is a function which returns the Widget and second is itemCount which is the length of an array of products.

Now, import this products.dart file inside the main.dart file.

// main.dart

import 'package:flutter/material.dart';

import './products.dart';

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

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  List<String> _products = [];

  @override
  void initState() {
    super.initState();
    _products.add('Laptop');
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        theme: ThemeData(primarySwatch: Colors.deepPurple),
        home: Scaffold(
            appBar: AppBar(title: Text('Long List App')),
            body: Column(children: [
              Container(
                  margin: EdgeInsets.all(10.0),
                  child: RaisedButton(
                      color: Theme.of(context).primaryColor,
                      splashColor: Colors.blueGrey,
                      textColor: Colors.white,
                      onPressed: () {
                        setState(() {
                          _products.add('Laptop');
                        });
                      },
                      child: Text('MacBook'))),
              Expanded(child: Products(_products))
            ])));
  }
}

Here, we have used the Expanded widget. It allows us expands a child of a RowColumn, or Flex. Using an Expanded widget makes the child of a RowColumn, or Flex expand to fill the available space in the primary axis (e.g., horizontally for a Row or vertically for a Column). If multiple children are expanded, an available space is divided among them according to the flex factor.

Here, we have passed the imported Products constructor with the argument of the _products array.

Save the file and restart the compilation using the shortcut key and now, add the more than 3 products and see that we are now getting the perfect scrollable view and it will display the product on demand.

This is the most efficient way to display a long list with the ListView by not exactly using ListView but using ListView.builder() constructor.

ListView.builder() Widget Example

 

Finally, Flutter ListView Example | Displaying Dynamic Contents Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.