Flutter: Displaying Dynamic Contents using ListView.builder

Flutter: Displaying Dynamic Contents using ListView.builder

Flutter is a mobile App SDK by Google which helps in creating modern mobile apps for iOS and Android using a single(almost) code base. It’s a new entrant in the cross platform mobile application development and unlike other frameworks like React Native, it doesn’t use JavaScript but DART as a Programming Language.

Flutter is a mobile App SDK by Google which helps in creating modern mobile apps for iOS and Android using a single(almost) code base. It’s a new entrant in the cross platform mobile application development and unlike other frameworks like React Native, it doesn’t use JavaScript but DART as a Programming Language.

If you’re new to Flutter, It’s highly recommended to read my first post “Flutter: From Zero To Comfortable”to get a good sense of how Flutter widgets work. You may also read my other stories on Flutter to get an overall view of different type of flutter widgets

What is meant by Dynamic Contents?

Unless an app is very basic and created for learning purposes, it will always use dynamic data i.e. Contents of the screen will change based on user actions and/or with change in network data.

Most of the time, the dynamic behaviour is achieved by changing the contents that is being displayed in the body. Flutter provides ListView.builder which can be used to generate dynamic contents from external sources.

Using ListView.builder(…)

ListView.builder is a way of constructing the list where children’s (Widgets) are built on demand. However, instead of returning a static widget, it calls a function which can be called multiple times (based on itemCount ) and it’s possible to return different widget at each call.

For example, let’s create a simple application containing basic MaterialApp with Scaffold contains AppBar and Body

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext ctxt) {
    return new MaterialApp(
      home: new ListDisplay(),
    );
  }
}
class ListDisplay extends StatelessWidget {
  @override
  Widget build (BuildContext ctxt) {
    return new Scaffold(
      appBar: new AppBar(title: new Text("Dynamic Demo"),),
      body:  // ListView.builder() shall be used here.
      ),
    );
  }
}

To use ListView.builder, we have to create an instance of it by calling its constructor using new , it takes multiple parameters, however, two of them are of special importance. They are

  1. itemCount
  2. itemBuilder

The itemCount parameter decides how many times the callback function in itemBuilder will be called.

To demonstrate the same, let’s assume that we have a global list like this in our application

List<String> litems = ["1","2","Third","4"];

Let’s use the ListView.builder(...) to display the list item in the body. The code for the same shall look like this

body: new ListView.builder
  (
    itemCount: litems.length,
    itemBuilder: (BuildContext ctxt, int index) {
     return new Text(litems[index]);
    }
  )

In here, the in-place callback function shall be called 4 times and each call will generate a Text Widget which shall be displayed in the body.

We can also write a separate function which can be called from itemBuilder as

// A Separate Function called from itemBuilder
Widget buildBody(BuildContext ctxt, int index) {
  return new Text(litems[index]);
}
body: new ListView.builder
(
  itemCount: litems.length,
  itemBuilder: (BuildContext ctxt, int index) => buildBody(ctxt, index)
),

In both the cases the output shall look like

We can use ListView.builder(..) in Stateless Widgets if we want to display dynamic (different) contents every time the widget is loaded within an application. With Stateful widgets, it can change the contents of the screen dynamically.

ListView.builder(…) with Stateful Widgets

Let’s first convert the existing widget as a Stateful widget by changing the code as

class ListDisplay extends StatefulWidget {
  @override
  State createState() => new DyanmicList();
}
class DyanmicList extends State<ListDisplay> {
  @override
  Widget build (BuildContext ctxt) {
      return new Scaffold(...)
}

To properly understand the usage of ListView.builder(..) in a stateful widget, let’s create a very simple ToDo app with Stateful Widget. We’ll create a Text input area (i.e TextField which allows one to add user defined items in the ToDo list. As soon as the item is added in the ToDo list, it will be automatically displayed onto the screen.

Since we’ll be creating more than one widget in Body: , we have to use a widget which is capable of holding multiple widgets like Column: , However, ListView.builder(...) will not work under Column unless its wrapped inside the Expanded widget. The Expanded widget allows Column elements to expand and fill the available space in the main axis, which is needed by ListView.builder(...)

So the overall hierarchy shall look like

To add text items into the list, we need an empty list and TextEditingController

List<String> litems = [];
final TextEditingController eCtrl = new TextEditingController();

Here is how the TextField widget shall be created.

new TextField(
  controller: eCtrl,
  onSubmitted: (text) {
    litems.add(text);  // Append Text to the list
    eCtrl.clear();     // Clear the Text area
    setState(() {});   // Redraw the Stateful Widget
  },
),

Nothing shall be changed in the implementation of ListView.builder(...) but it will be wrapped inside Expanded widget

new Expanded(
    child: new ListView.builder
      (
        itemCount: lItems.length,
        itemBuilder: (BuildContext ctxt, int Index) {
          return new Text(lItems[Index]);
        }
    )
)

And we’re ready to dynamically change the contents of the screen. Here is how the action shall look like

Here is the complete code for class DynamicList

That’s all for this particular post. I hope I was able to explain how we can use ListView.builder(...) for generating dynamic contents.

Thanks for reading….!!!

Further reading:

Flutter & Dart - The Complete Flutter App Development Course ☞ http://learnstartup.net/p/r14fuKRpz

Flutter and the Command Line ☞ https://morioh.com/p/5b18751743c6/

How to create custom icon in Flutter ☞ https://morioh.com/p/5a444ac4c914/

Flutter Tutorial For Beginners - Build Your First Flutter App ☞ https://morioh.com/p/353ba3d9d55e

Real-World Projects with Flutter ☞ http://learnstartup.net/p/eXwwYUr2y

flutter mobile-apps

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Google's Flutter 1.20 stable announced with new features - Navoki

Google has announced new flutter 1.20 stable with many improvements, and features, enabling flutter for Desktop and Web

Top 25 Flutter Mobile App Templates in 2020

Flutter has been booming worldwide from the past few years. While there are many popular mobile app development technologies out there, Flutter has managed to leave its mark in the mobile application development world. In this article, we’ve curated the best Flutter app templates available on the market as of July 2020.

How To Succeed In Mobile App Wireframe Design?

This article covers everything about mobile app wireframe design: what to do and what not, tools used in designing a mobile or web app wireframe, and more.

How much does it cost to make a Flutter app for your business?

Get a Free Quote on Android App Development, iPhone App Development, Ionic App Development, Video Development, ASO, SEO, Google Ads/Adwords, SEO for your app Idea.

Flutter – A Boon to Mobile App Developers

Flutter app development is in trend; ever since flutter - the mobile app development framework, has been helping app developers to build amazing applications.