How to use list in Flutter

One of the most common collection in every programming language is List. It is also known as array in other programming language. The list in Flutter is an ordered group of objects. We commonly call them lists.

The list plays a very important role in any Flutter App. You may ask why?

The answer is quite simple.

Any small to medium, or a big Flutter App needs to place data in order. Right? Take a look at this Flutter App.


Flutter App using List example one
Flutter App using List example one

We have two separate lists of questions and answers. As a built in data type, list in Flutter allows any data “Type”. That means, if we keep our list objects in a Class, we can call the list by mentioning that class data Type. We will see a lot of examples later.

Anyway, it is always easy to find any particular element when they are placed in ordered list.

Because an ordered list has an index that starts from 0, we can easily track that index number and find out the element.

In addition, Flutter and Dart comes with plenty of methods that we can use to handle the List.

Before we jump in to learn how we have built this simple “English Test App” let us some list examples in Dart console.

Watch the output, that will also clarify how list in Flutter and Dart works.

void main() {
  
  IntroToList question = IntroToList();
  
  print(question.questions.length); // 4
  
  print(question.questions.reversed);
  
  /**
   * (The synonym of scorn is despise., 
   * The sound a Frog makes is known as croak., 
   * A young horse is called a duckling., 
   * 640 acres equal 1 square mile.)* 
   * 
   * */
  
  print(question.questions.firstWhere((i) => i.length > 1)); 
  // 640 acres equal 1 square mile.
  
  print(question.questions.first);
  // 640 acres equal 1 square mile.
  
  print(question.questions.every((element) => element.startsWith('a')));
  // false
  // because every element does not start with letter 'a'
  
  
  
  question.checkAnswer(1); 
  // Corerct Answer was: A young horse = a duckling.  
  question.checkAnswer(3); 
  // The synonym of scorn is despise.
  
  for (final q in question.questions) {
    print(q);
  }
  
  /**
   * <<< OUTPUT>>>
 640 acres equal 1 square mile.
A young horse is called a duckling.
The sound a Frog makes is known as croak.
The synonym of scorn is despise.
   * 
   * 
   *  */
  
}

class IntroToList {
  
  List<String> questions = [
    '640 acres equal 1 square mile.',
    'A young horse is called a duckling.',
    'The sound a Frog makes is known as croak.',
    'The synonym of scorn is despise.',
  ];

  int questionIndex = 0;

  List<bool> answers = [
    true,
    false,
    true,
    true,
  ];

  String check = '';

  void checkAnswer(int questionIndex) {
    
    if (questionIndex == 0) {
      check = '';
    } else if (questionIndex == 1) {
      check = questions[questionIndex];
    } else if (questionIndex == 2) {
      check = questions[questionIndex];
    } else if (questionIndex == 3) {
      check = questions[questionIndex];
    } else if (questionIndex > 3) {
      check = questions[questionIndex];
    }
    
    print(check);
  } 
  
}

What we see above is just a glimpse. There are plenty of other methods that Dart and Flutter List uses.

However, we do not have to use them all. In fact, a very few of the methods are used while we build a Flutter App.

In the coming sections, we will see how we can use List in Flutter to make different type of Applications.

To start with, let us build a Flutter App, that tests English knowledge. It is a simple App that displays a question. Below that question we have true and false button.

You press any button, and it will show the correct answer below. As a result, you know whether you have pressed the correct button, or not.

As we progress, we will make this Flutter App more interesting.

For the time being let us be simple in our approach so that we can understand the basic of Flutter lists.

Let us start with the top-level main() function which is our entry point.

import 'package:flutter/material.dart';

import 'view/app.dart';

void main() => runApp(const App());

Next, we create a “view” folder, in our root directory, and place the custom Widget App() there.

That will take us to the AppHomePage() Widget.

import 'package:flutter/material.dart';

import 'app_home_page.dart';

class App extends StatelessWidget {
  const App({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Introduction to List',
      home: AppHomePage(),
    );
  }
}

In the AppHomePage() Widget, we will declare two separate lists. One list will be a collection of questions, and the other will be answers.

However, two lists will be of different data type.

Let us take a look at the lists firstly.

List<String> questions = [
    '640 acres equal 1 square mile.',
    'A young horse is called a duckling.',
    'The sound a Frog makes is known as croak.',
    'The synonym of scorn is despise.',
  ];

  int questionIndex = 0;

  List<bool> answers = [
    true,
    false,
    true,
    true,
  ];

We must always declare the data type of the list items.

As we see, the first list has a data type String. Subsequently, the second list has data type Boolean. Therefore, it consists of true and false.

In between two lists, we have an index number which is of integer data type. We need to track, or iterate both lists at the same time. Consequently, we can track which button is pressed. True or false?

As the first list of questions shows, the second statement is false. Otherwise, the rest of the lists are true.

Therefore, we have made our second list of answers matching them in accordance with the questions.

Let us see the full code snippet now.

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

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

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

class _AppHomePageState extends State<AppHomePage> {
  List<String> questions = [
    '640 acres equal 1 square mile.',
    'A young horse is called a duckling.',
    'The sound a Frog makes is known as croak.',
    'The synonym of scorn is despise.',
  ];

  int questionIndex = 0;

  List<bool> answers = [
    true,
    false,
    true,
    true,
  ];

  String check = '';

  void checkAnswer() {
    if (questionIndex == 0) {
      check = '';
    } else if (questionIndex == 1) {
      check = 'Corerct Answer was: 640 acres = 1 square mile.';
    } else if (questionIndex == 2) {
      check = 'Corerct Answer was: A young horse = a foal.';
    } else if (questionIndex == 3) {
      check = 'Corerct Answer was: The sound a Frog makes = croak.';
    } else if (questionIndex > 3) {
      check = 'Corerct Answer was: The synonym of scorn = despise.';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.blue.shade900,
      appBar: AppBar(
        title: const Text('Introduction to List'),
      ),
      body: SafeArea(
        child: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Text(
                questions[questionIndex],
                textAlign: TextAlign.center,
                style: GoogleFonts.laila(
                  textStyle: Theme.of(context).textTheme.headline6,
                  fontSize: 30,
                  fontWeight: FontWeight.w900,
                  color: Colors.amber.shade400,
                ),
              ),
              buildButtonInsideContainer(
                'True',
                Colors.white,
              ),
              buildButtonInsideContainer(
                'False',
                Colors.black,
              ),
              Text(
                check,
                textAlign: TextAlign.center,
                style: GoogleFonts.caveat(
                  textStyle: Theme.of(context).textTheme.headline6,
                  fontSize: 20,
                  fontWeight: FontWeight.w700,
                  color: Colors.blue.shade50,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Container buildButtonInsideContainer(String answer, Color color) {
    return Container(
      padding: const EdgeInsets.all(10.0),
      child: ElevatedButton(
        onPressed: () {
          setState(() {
            answers[questionIndex];
            questionIndex++;
            checkAnswer();
          });
          if (questionIndex > 3) {
            questionIndex = 0;
          }
        },
        child: Text(
          answer,
          style: GoogleFonts.lato(
            textStyle: Theme.of(context).textTheme.headline6,
            fontSize: 20,
            fontWeight: FontWeight.w700,
            color: color,
          ),
        ),
      ),
    );
  }
}

Since both the Button Widgets inside a Container Widget, we have used a common function that return a Container Widget. As parameters we pass the “answer” and the “color”.

Why?

Because one answer might be “True”, or “False”.

However, we track the index number of question list, and each press moves the question forward.

Besides, through a simple if-else conditional, we track the index number and show the correct answer.

Watch the second question below.

The answer is false. As we know that young horse is known as a foal.

Therefore, if someone presses the “True” button, without knowing the correct answer, she will be informed immediately.


List in Flutter second example
List in Flutter second example

Suppose a user presses any button, by knowingly, or unknwoingly.

She will be notified and the third question will pop up at the same time.


Flutter list third example
Flutter list third example

Although we have shown the full code, still you may wish to clone the project and run it in your local machine.

In that case, please visit the respective branch of the GitHub repository.

In the next section we will try to make this Flutter App more object oriented.

So stay tuned, and happy Fluttering.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

Courses at Educative

GitHub repository

Technical blog

Twitter

Comments

2 responses to “How to use list in Flutter”

  1. […] our last section, we have built a Flutter Quiz App using List. However, we tried to do in a simple […]

  2. […] in Flutter is a collection of items. It is the most common collection where we keep ordered […]

Leave a Reply