What does "...switch(state)" do?

Hello
I’m new to Flutter and dart devleoping but with expiriences in c/cpp.

I tried the a tutorial from the bloc lib and everythink is working and seams to be clear but I struggle with the meaning of “…” before the switch.

Question:

  1. What does “…switch(state)” mean?
  2. How does the “…” is called?
 Widget build(BuildContext context) {
    return BlocBuilder<TimerBloc, TimerState>(
      buildWhen: (prev, state) => prev.runtimeType != state.runtimeType,
      builder: (context, state) {
        return Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            ...switch (state) { 
              TimerInitial() => [
                  FloatingActionButton(
                    child: const Icon(Icons.play_arrow),
                    onPressed: () => context
                        .read<TimerBloc>()
                        .add(TimerStarted(duration: state.duration)),
                  ),
                ],
              TimerRunInProgress() => [

Source: Flutter Timer | Bloc Last Visit: 30.11.2024 15:37

If variable state is an instance of TimerInitial do this, if an instance of TimerRunInProgress do that.

1 Like

Thanks for the response.

Maybe i should have mention it before that i know how switch case is working. It is really only about the 3 dots before the switch “…”.

I know it is very basic question but i can’t find any information. Searching “…” will not give an proper result. :smile:

1 Like

That is the “spread operator”. It is used to “unpack” one collection and place the contents into another collection. In your code example, Row wants a List of Widgets (“children”); if the state is TimerInitial, children is being populated by a List of one FloatingActionButton.

I’m not that experienced with Flutter, so I haven’t seen this kind of usage before. I’ve more seen ... used to fill out a Column’s children, converting items one-by-one into Widgets.

// names is a List of Strings
// we want a list of Widgets
Column(
  children: [
    ...names.map((name) {
      return Text(name)
    })
  ]
)

Here is a reference to ... in the Dart docs, though it doesn’t say much.

2 Likes
final anotherArray = [8, 9];
final something = [1, 2, 3, ...anotherArray, 4, 5];

print(something);

Response: 1, 2, 3, 8, 9, 4, 5.

In Dart (and in other languages) you can put code inside an array, so the compiler will interpolate it.

You can add other arrays, if, switch, for, etc.

Details here: Collections | Dart and Operators | Dart

2 Likes