How to use Spread Operator(…) in Flutter

How to use Spread Operator(...) in Flutter

In this guide, we will discuss how to implement a Spread Operator in a flutter. For this, we should know some basic information about what a spread Operator in flutter is.

Since version 2.3, Dart adds a new operator called spread which uses three dots (...) notations. which can be used to extend the elements of a Collection. It is very useful and has a quick syntax for adding items to arrays, combining arrays. In Dart, Spread Operator (…) and Null-aware Spread Operator (…?) are used for inserting multiple elements in a collection like Lists, Maps, etc

Now we will learn some basic spread operators through a simple List.

  List<int> list1 = [1, 2, 3, 4, 5];
  List<int> data = [0, ...list1];
  print(data);

In the above, code the data is generated by concatenating element (0) with a List (list1). The output will be [0, 1, 2, 3, 4, 5]

We can also use triple-dot for combining two List instances at the same time which is shown below the example.

  var s = ['sagar', 'koju'];
  var s1 = ['flutter', 'developer'];
  var s2 = [...s, ...s1, ];
  print(s2);

The variable s2 will be concatenating with the variable s and s1 which produce the output given below [sagar, koju, flutter, developer]

What happens if we try to use the spread operator with a null List which is shown below with the example.

  var s = ['sagar', 'koju'];
  var s3 = null;
  var s2 = [...s, ...s3];
  print(s2);

We will get the following error while debugging these codes:

Unhandled exception:
type 'Null' is not a subtype of type 'Iterable<dynamic>'
#0      main (file:///E:/flutter/Dart/List/spread_operator.dart:5:22)
#1      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
#2      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
PS E:\flutter\Dart\List>

Dart also supports a null-aware operator for spread. Just we will add ? a symbol after the triple-dot… which is shown below.

  var s = ['sagar', 'koju'];
  var s1 = ['flutter', 'developer'];
  var s3 = null;
  var s2 = [...s, ...s1, ...?s3];
  print(s2);

Here in the above example when we use the null-aware operator, the value will be checked first and if it’s, it will be ignored. The Output will be shown below. [sagar, koju, flutter, developer]

We can also use if condition to determine whether the List should be concatenated or not.

  List<int> list1 = [1, 2, 3];
  List<int> list2 = [4, 5];
 
 bool condition = false;

  List<int> result = [...list1, if (condition) ...list2];
  print(result);

The output will be [1, 2, 3]. Here list2 will not display its value because we have to use the condition to check list2. initially, we have declared that list2 has false so it ignores the value of list2 and displays the value of list1.

Now we will implement the spread operator in a flutter. First of all, let’s create a ListTile containing a few texts.

import 'package:flutter/material.dart';

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Spread Operator in Flutter'),
        centerTitle: true,
      ),
      body: Column(
        children: const [
          ListTile(
            title: Text('Apple'),
          ),
          ListTile(
            title: Text('Banana'),
          ),
          ListTile(
            title: Text('Mango'),
          ),
          ListTile(
            title: Text('Grape'),
          ),
          ListTile(
            title: Text('WaterMelon'),
          ),
          ListTile(
            title: Text('Orange'),
          ),
          ListTile(
            title: Text('Papaya'),
          ),
          ListTile(
            title: Text('Coconut'),
          ),
        ],
      ),
    );
  }
}

Meanwhile, when we run this application in the emulator or device, we should get the UI similar to the screenshot below:

We can simply modify the above code by using the spread operator to get the same output.

import 'package:flutter/material.dart';

class SpreadOperatorScreen extends StatelessWidget {
  SpreadOperatorScreen({Key? key}) : super(key: key);
  List<String> data = [
    'Apple',
    'Banana',
    'Mango',
    'Grape',
    'WaterMelon',
    'Orange',
    'Papaya',
    'Coconut',
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Spread Operator in Flutter'),
        centerTitle: true,
      ),
      body: Column(
        children: [
          ...data
              .map((e) => ListTile(
                    title: Text(e),
                  ))
              .toList(),
        ],
      ),
    );
  }
}

Hence with the help of the spread operator, we have finally got the same output with fewer minimal lines of code by using the spread operator.

Thanks for reading this article on How to Use Spread Operator(…) in Flutter.

Also Read: Riverpod As An StateManagement