Flutter / Dart: Problem Using the Spread Operator After The Else Clause Of A Ternary

Viewed 1180

In my Flutter app, I'm trying to use the Dart spread operator (ie-...) at the else section of a ternary operator in the build() method of one of my widgets.

ie-

class SearchCriteriaState extends State<SearchCriteria> {
  List<SearchParameters> listSearchParam = [];

  Widget build(BuildContext context) {
    return Column(
       children: [
         Text('hey there'),
         listSearchParam.isEmpty 
           ? Text ('Empty
           : ...listSearchParam.map((param)=>Text(param.toString()).toList(),
       ],
    );
  }
}

The code above will not compile, getting the error below with the spread statement underlined in red.

Expected to find ','.dart(expected_token)

If I replace the whole ternary with just the spread statement, it will compile and run (except it doesn't deal with the edge condition where the list is empty).

Any ideas?

The workaround I'm using currently is to wrap the spread statement in another Column() which works, but is fugly ('scuse my French).

I had already searched for similar issues and the closest I could find was also a problem with using the spread operator in a ternary but in the context of webpack which I'm assuming is with React.

All suggestions much appreciated.

/Joselito

1 Answers

Please use if else.

import 'package:flutter/material.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final List<String> texts = <String>['1', '2', '3'];
    final bool test = false;

    return MaterialApp(
      home: Scaffold(
        body: Column(
          children: [
            const Text('asdf'),
            if (test)
              const Text('test is TRUE')
            else
              ...texts.map((e) => Text(e)).toList(),
          ],
        ),
      ),
    );
  }
}
Related