Flutter Widgets → Flutter ListView – Camposha

Flutter Widgets

Flutter Widgets

Flutter Widgets

Flutter ListView

Flutter ListView Tutorial and Examples.

In this tutorial we want to look at one of the most important widgets especially when it comes to rendering lists of data, the ListView.

What is a ListView?

A ListView is a scrollable list of widgets arranged linearly.

As the names suggests it’s responsibility is list items. These items can then scrolled. ListView isn’t the only scrolling view. There are others like gridview, however ListView is the most commonly used.

ListView will display its children one after another in the scroll direction. In the cross axis, the children are required to fill the ListView.

Here’s a simple infinite listview:

new ListView.builder(
  padding: new EdgeInsets.all(8.0),
  itemExtent: 20.0,
  itemBuilder: (BuildContext context, int index) {
    return new Text('entry $index');
  },
)

More ListView documentation can be found here.

Let’s look a flutter ListView example with onClick.

Why ListView?

Well ListViews are probably the most commonly used widgets for displaying lists of data. In most cases we use it together with CardViews. And in fact render images and text. You may have already seen countless apps with lists of images and text.

If it is flutter application, then chances are that either gridview or listview has been used.

ListViews and GridViews are important because given the nature(small screen) of mobile devices, you always need to have the ability to scroll through data. The screen can only display a small of data per viewport. So we need a component that can easily be scrolled.

Also the fact that most of mobile apps by their nature require the ability to show lists of data. Mobile apps are not mostly used for heavy data entry like Microsoft Word, Excel etc in PC. Rather majority of apps require us to fetch data from the server and render to the user. These types of apps need widgets like ListViews.

1. Flutter Simple ListView with OnClick Example

This is a simple flutter listview example to display items from a flutter fixed-length list, otherwise known as an array in other languages. Obviously we write our app in Dart programming language.

Flutter ListView
Flutter ListView

 

If the user clicks a single cardview, a CupertinoAlertDialog will be rendered with the clicked item.

The dialog will have some text and icon.

And here’s our video tutorial:

Here are the files we explore:

  1. pubspec.yaml
  2. lib/main.dart
(a). pubspec.yaml
name: simple_listview
description: A Simple ListView Flutter application.

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^0.1.2

dev_dependencies:
  flutter_test:
    sdk: flutter
flutter:
  uses-material-design: true
(b). main.dart

This is where we write our flutter code in dart programming language. In Dart it is very common to write several classes in a single file. So this simple file will have three classes.

Importing Packages in Flutter/Dart

But first we need to import some packages and we do that using the import keyword in dart.

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';

Here are the packages we are importing:

  1. material.dart : will give us material design widgets and theme.
  2. cupertino.dart : Will give us CupertinoAlertDialog as well as cupertino icons.
Creating classes in Flutter/Dart

In Dart like in most C style programming languages you create a class using the class keyword. Classes are encapsulation mechanism in Object Oriented Programming languages.

In this case we create three classes:
1.class MyApp extends StatelessWidget {..}

  1. class Home extends StatefulWidget {..}
  2. class _HomeState extends State<Home> {..}

Our first class is deriving from StatelessWidget and implementing the build() method. That method will build a materialapp widget with title, home and theme set and return it as a widget.

The second class will derive from StatefulWidget and override the createState() method.

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter ListView',
      home: new Home(),
      theme: new ThemeData(primaryColor: Colors.orange),
    );
  }
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => new _HomeState();
}

class _HomeState extends State<Home> {

  @override
  Widget build(BuildContext context) {
    var spacecrafts = ["James Web","Enterprise","Hubble","Kepler","Juno","Casini","Columbia","Challenger","Huygens","Galileo","Apollo","Spitzer","WMAP","Swift","Atlantis"];
    var listItem = new ListView.builder(
      itemCount: spacecrafts.length,
      itemBuilder: (BuildContext context, int index) {
        return new ListTile(
          title: new Card(
            elevation: 5.0,
            child: new Container(
              alignment: Alignment.centerLeft,
              margin: new EdgeInsets.only(top: 10.0, bottom: 10.0),
              child: new Text(spacecrafts[index]),
            ),
          ),
          onTap: () {
            showDialog(
                barrierDismissible: false,
                context: context,
                child: new CupertinoAlertDialog(
                  title: new Column(
                    children: <Widget>[
                      new Text("ListView"),
                      new Icon(
                        Icons.favorite,
                        color: Colors.red,
                      ),
                    ],
                  ),
                  content: new Text( spacecrafts[index]),
                  actions: <Widget>[
                    new FlatButton(
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                        child: new Text("OK"))
                  ],
                ));
          },
        );
      },
    );

    return new Scaffold(
      appBar: new AppBar(
          title: new Text("Flutter ListView")
      ),
      body: listItem,
    );
  }
}
void main() {
  runApp(new MyApp());
}

Flutter ListView with Images and text

Let’s look at a simple example to render images/icons and text in a ListView in ListTiles. This is a very basic example.

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build (BuildContext context){
    final title = 'Basic List';
    return MaterialApp(
      title: title,
      home: Scaffold(
        appBar: AppBar(
          title: Text(title),
        ),
        body: ListView(
          children: <Widget>[
            ListTile(
              title: Text('Map'),
              leading: Icon(Icons.map),
            ),
            ListTile(
              title: Text('Photo Album'),
              leading: Icon(Icons.photo_album),
            ),
            ListTile(
              title: Text('Phone'),
              leading: Icon(Icons.phone),
            ),
          ],)
      )
    );
  } 
}

Leave a Reply

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

Rating

Not enough ratings to display
Join Us
X