How To Use The map() Function In Dart

Benjamin Carlson
2 min readApr 28, 2021
picture of a world map

Read this post with code syntax highlighting on Coffeeclass.io.

The Problem

Recently, I was building a Flutter app and I needed to map over an array of users when a user logged in and check if their username, password, and security question answer matched what was in the database (the userArray). I tried to do something like this:

var userArray = ['User 1', 'User 2', 'User 3'];

userArray
.map((user) => {
if (user == 'User 1')
{
// log user in
} else {
// don't log user in
}
});

Quick note: I removed some of my project specific logic and only included the important parts so it is easier to follow.

This code logs the user in if they are user 1. This looks like it should work, right? Unfortunately, it doesn’t. It will not break either. Instead, nothing will happen. This makes it hard to debug.

The Solution

The simple solution is to add .toList() to the end of the map statement.

var userArray = ['User 1', 'User 2', 'User 3'];

userArray
.map((user) => {
if (user == 'User 1')
{
// log user in
} else {
// don't log

--

--

Benjamin Carlson
Benjamin Carlson

Written by Benjamin Carlson

Software Developer, creator, and writer living and working in CT. I write about coding, finance, startups, and more!

No responses yet