Map through a List Flutter: NoWar App – Step 1

We are going to build a NoWar Flutter App. While we build this app, we will discuss a few important list-concepts in Flutter and Dart. We will use various list methods. And one of them is the list.asMap() method.

Firstly, let us see how the home page of this NoWar app will look like.

Secondly, we will discuss the list method that we have used in the home page.

Finally, we will build the whole app.

No War App Homepage first
No War App Homepage first

This is the home page which we can scroll down to see other parts. As we scroll down, we will find more topics that we need to build.

In addition, there will be other pages as well.

Therefore, as a whole, we will use the ‘routes’ property of the MaterialApp widget in a correct way.

Why?

Because we need to pass correct data. Besides, we will also design those pages.

The middle of the page will look as follows as we scroll down.

No War App Homepage second
No War App Homepage second

In the middle part, we need a route to the page where we will display what kind of weapons used in the last three centuries.

In addition, as our civilisation progresses, the style of war has changed a lot. Therefore, we have added a page that discuses cyber warfare.

That is the lower part of our NoWar app.

No War App Homepage third
No War App Homepage third

What is Dart list asMap method?

In the upper part of the home page, we have three icons. These icons represent last three centuries.

Of course, we could have hard coded those icons one after another. But we will not do that.

Instead, we create a list of three icons and an index property, as follows.

int _selectedIndex = 0;
final List _icons = [
    '1700',
    '1800',
    '1900',
  ];

After that, we will map this list one after another so that the key represents the index, and the values are the elements at each index.

Let us a define it inside a Widget method like below.

 Widget _buildIcons(int index) {
    return GestureDetector(
      onTap: () {
        setState(() {
          _selectedIndex = index;
        });
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => const AllWars()),
        );
      },
      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(
          '${_icons[index]}',
          textAlign: TextAlign.center,
          style: TextStyle(
            fontSize: 25.00,
            fontFamily: 'Trajan Pro',
            fontWeight: FontWeight.bold,
            color: _selectedIndex == index
                ? Theme.of(context).primaryColor
                : Colors.red,
          ),
        ),
      ),
    );
  }

The above method will pass the index as key. Besides, it returns a Gesture Detector widget. As a result we can tap any of the icon, and reach a page.

Now, inside, the home page widget, we are going to use the Dart list asMap() method.

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: ListView(
          padding: const EdgeInsets.all(32),
          children: <Widget>[
            Text(
              'NO TO WAR!',
              style: TextStyle(
                  fontSize: 55.0,
                  fontWeight: FontWeight.normal,
                  fontFamily: 'Trajan Pro',
                  foreground: Paint()
                    ..color = Colors.red
                    ..strokeWidth = 2.0
                    ..style = PaintingStyle.stroke),
            ),
            const SizedBox(
              height: 20.00,
            ),
            Text(
              'Let\'s Learn From the Bloody War History. Stop War Now!',
              style: TextStyle(
                  fontSize: 25.0,
                  fontWeight: FontWeight.normal,
                  fontFamily: 'Trajan Pro',
                  foreground: Paint()
                    ..color = Colors.blue
                    ..strokeWidth = 2.0
                    ..style = PaintingStyle.stroke),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: _icons
                  .asMap()
                  .entries
                  .map((MapEntry map) => _buildIcons(map.key))
                  .toList(),
            ),
            const SizedBox(
              height: 20.00,
            ),
            const TopBattleController(),
            const SizedBox(
              height: 20.00,
            ),
            const WeaponController(),
            const SizedBox(
              height: 20.00,
            ),
            const CyberController(),
          ],
        ),
      ),
    );
  }
}

As a result, we can display the last three centuries in a Row.

Map through a list in Flutter

List of Icons in a Row Widget
List of Icons in a Row Widget

In this section we will concentrate how we have used the List asMap() method. Certainly, we can map a list in Flutter other way also.

Therefore, let us a take a close look at that part now.

Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: _icons
                  .asMap()
                  .entries
                  .map((MapEntry map) => _buildIcons(map.key))
                  .toList(),
            ),

To understand this list method, let’s consider a simple example first.

void main() {
  
  List<String> words = ['A', 'B', 'C', 'D'];
  
  words.asMap().forEach((index, value) => print(value));
  
}
// output
A
B
C
D

Let’s add two more lines to the above code that will clarify the home page code.

print(map[0]);   // 'A';
map.keys.toList(); 

Now, let’s take a look at the whole code again.

Let us redefine the code in a new way where we can get the key as index, and value as the element at that index position.

void main() {
  
  List<String> words = ['A', 'B', 'C', 'D'];
  
  words.asMap().entries.map((MapEntry map) => print('${map.key} : ${map.value}')).toList();
  
}

// output:
0 : A
1 : B
2 : C
3 : D

We have displayed the list of icons in the same way.

Our next task will be to build three separate pages that will represent three centuries.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

Courses at Educative

GitHub repository

Technical blog

Twitter

Comments

One response to “Map through a List Flutter: NoWar App – Step 1”

  1. […] have already seen the First Step where we have mainly built the home page. In this section, we will build a few other pages. In […]

Leave a Reply