Map() Method in Dart | Flutter

The map() method does not modify the original collection; it returns a new collection with the transformed values. If you want to modify the original collection, you can assign the result of the map() method back to the original collection variable, like this:


numbers = numbers.map((number) => number * 2).toList();

 

Example 1:

void main() {
  final numList = [10, 15, 20, 25, 30];

  numList.map((e) => print(e)).toList();
}


Example 2:

void main() {
  final numList = [10, 15, 20, 25, 30];

  var result = numList.map((e) => e + 1).toList();

  print(result);
}


Example 3:
import 'package:flutter/material.dart';
import 'package:flutter_demo/home_page.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<String> colorList = [
    'Red',
    'Blue',
    'Green',
    'White',
    'Yellow',
  ];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: colorList
              .map(
                (e) => Center(
                  child: Card(
                    color: Colors.green,
                    child: Padding(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 20, vertical: 20),
                      child: Text(e),
                    ),
                  ),
                ),
              )
              .toList(),
        ),
      ),
    );
  }
}

Video Link:


Post a Comment (0)
Previous Post Next Post