How do you Map a dart list in Flutter?

To map a Dart list in Flutter, we need to know one thing first.

Flutter layout widgets like Column, Row, or Wrap always has children that returns a List. Not a Map.

As a result, in some circumstances, we need to map a dart list in flutter as per our requirements.

We have a lot of articles on Flutter List and Map, however, we need to understand the relationship between Dart List and Map in flutter.

Let us first see, how we can map a list in pure dart console programming.

Let us have a Student class and

class Student {
  String name;
  int age;

  Student({
    required this.name,
    required this.age,
  });
}

And, we can create a List of some Student objects in Dart.

import 'package:dart_common_problems/student.dart';

List<Student> students = [
  Student(
    name: 'John',
    age: 10,
  ),
  Student(
    name: 'Json',
    age: 11,
  ),
  Student(
    name: 'Allen',
    age: 9,
  ),
  Student(
    name: 'Maria',
    age: 8,
  ),
  Student(
    name: 'Becky',
    age: 10,
  ),
];

Now, in our bin folder we can map this Dart list, quite easily.

import 'package:dart_common_problems/students.dart';

void main(List<String> arguments) {
  var map1 = {for (var e in students) e.name: e.age};
  print(map1);
  var map2 = students.asMap().entries.map((e) => e.value);
  print(map2);
  var map3 = students.asMap().entries.map((e) => e.key);
  print(map3);
  var map4 = students.asMap().entries.map((e) => e.key);
  print(map4.toList().length);
}

Let us first check the outputs of the lines first. Then we will discuss the code.

{John: 10, Json: 11, Allen: 9, Maria: 8, Becky: 10}

(Instance of 'Student', Instance of 'Student', Instance of 'Student', 

Instance of 'Student', Instance of 'Student')

(0, 1, 2, 3, 4)

5

In the first line, we get each student’s name and age as we loop through the List of instantiated students.

But in the second line, firstly, we map the Dart list with asMap() method. Secondly we go through each entries and this time we use map() method to get the key and value respectively.

Quite naturally, as value we’ve got five instances of Student class. And as key, we get the index of each list item.

However, we can convert that map into List again and count the length.

As expected, we’ve got the number 5.

Now, question is can we do the same thing in Flutter?

How do I convert a map to a List in flutter?

Yes, we can do the same thing in Flutter and get the length of the Students objects. Even we can pass that length as Navigator arguments and get an output just like before.

Subsequently, we can pass each index of the Student object also and navigate to another page and see the details.

We can do that either using Provider data model and ChangeNotifierProvider or we can use Widget class constructors.

However, this time we want to understand how we can map a dart list in flutter.

Therefore, we’ll take the same example that we’ve just seen in the Dart console application. Consequently we’ll try to apply that same example in our Flutter app.

For brevity we’ll see the code in parts. Although you’ll get the full code snippet in the respective GitHub repository.

Firstly, we’ll create a home page where we define the route and navigation.

import 'package:flutter/material.dart';
import 'package:shop_app_with_provider/list-map-navigation/all_pages.dart';

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'List Map and Navigation',
      home: FirstPage(),
      routes: {
        AllPage.routename: (context) => const AllPage(),
      },
    );
  }
}

Secondly, we define a Student class as we’ve defined in our Dart console application.

class Student {
  String id;
  String name;
  int age;

  Student({
    required this.id,
    required this.name,
    required this.age,
  });
}

In the above code we’ve made a little change. We’ve added one more property ID to Student class.

It’ll help us to navigate and find all details of a particular student.

Now, we can instantiate ten Student objects inside the our first page stateless widget.

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

  /* final List _icons = [
    '1700',
    '1800',
    '1900',
  ]; */

  final List<Student> students = [
    Student(
      id: 's1',
      name: 'John',
      age: 10,
    ),
    Student(
      id: 's2',
      name: 'Json',
      age: 11,
    ),
    Student(
      id: 's3',
      name: 'Allen',
      age: 9,
    ),
    Student(
      id: 's4',
      name: 'Maria',
      age: 8,
    ),
    Student(
      id: 's5',
      name: 'Becky',
      age: 10,
    ),
    Student(
      id: 's6',
      name: 'John',
      age: 10,
    ),
    Student(
      id: 's7',
      name: 'Json',
      age: 11,
    ),
    Student(
      id: 's8',
      name: 'Allen',
      age: 9,
    ),
    Student(
      id: 's9',
      name: 'Maria',
      age: 8,
    ),
    Student(
      id: 's10',
      name: 'Becky',
      age: 10,
    ),
  ];

...

Thirdly, we need a custom widget to get the length of the all Student list.

Widget _buildIcons(BuildContext context, int index) {
    final List x = students.asMap().entries.map((e) => e.key).toList();
    final int y = x.length;
    return GestureDetector(
      onTap: () {
        Navigator.of(context).pushNamed(
          AllPage.routename,
          arguments: y,
        );
      },
      child: Container(
        margin: const EdgeInsets.all(10.0),
        width: 80.0,
        height: 40.0,
        alignment: Alignment.center,
        decoration: const BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(30.00)),
          boxShadow: [
            BoxShadow(
              color: Colors.red,
              blurRadius: 4.00,
              spreadRadius: 2.00,
            ),
          ],
          gradient: LinearGradient(
            begin: Alignment.centerLeft,
            end: Alignment.centerRight,
            colors: [
              Colors.yellow,
              Colors.white,
            ],
          ),
        ),
        child: Text(
          '$index',
          textAlign: TextAlign.center,
          style: const TextStyle(
            fontSize: 25.00,
            fontFamily: 'Trajan Pro',
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }

...

Our next challenge is to map a Dart list in Flutter.

Just like the Dart console application code, we’ve used the map() method to map the List of Students objects that have already been instantiated.

As a result, this part of the above code is quite self explanatory.

final List x = students.asMap().entries.map((e) => e.key).toList();
    final int y = x.length;
    return GestureDetector(
      onTap: () {
        Navigator.of(context).pushNamed(
          AllPage.routename,
          arguments: y,
        );
      },

Now, we’re in a position to navigate to another page, here All Pages stateless widget, and pass the length of the List of instantiated Students objects there.

How do you Map a dart list?

Now we must use iterable map() method as we have seen in our Dart console application above.

var map4 = students.asMap().entries.map((e) => e.key);
  print(map4.toList().length);

However, replicate the same code in Flutter and retrieve all the Student object individually in Flutter requires further operations.

To sum up, we know, that Flutter returns a list of widgets as children through some layout widgets like Row, Wrap, ListView or Column.

For example, in our custom first page widget, it has done the same.

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('List, Map and Navigation'),
      ),
      body: Wrap(
        children: students
            .asMap()
            .entries
            .map((MapEntry map) => _buildIcons(context, map.key))
            .toList(),
      ),
    );
  }

Now, if we compare the above code with the Dart console code, then we’ll understand how Flutter uses map() method and passes MapEntry object and passes the map key to the _buildIcons() method.

However, we need to convert it to a List.

Why?

Because the Wrap children returns a List of widgets.

Now, we can run our app, and see the output where it displays the index or key of each instance of Student object.

Map a Dart List in Flutter
Map a Dart List in Flutter

As we have already used the GestureDetector onTap() method to navigate to another screen, we can see how many students are there in the class.

Get the length pf List length in Flutter
Get the length pf List length in Flutter

Our next challenge will be to get student details in this screen. So that we can display student’s name individually on the home page, and if we tap each student name, we’ll arrive in this screen to get the details.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

GitHub repository

Technical blog

Twitter

Comments

One response to “How do you Map a dart list in Flutter?”

  1. […] How do you Map a dart list in Flutter? […]

Leave a Reply