How To Use The map() Function In Dart
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…