Spread operator in const collection literals

The feature spec describes being able to write code like

const list = [2, 3];
const another = [1, ...list, 4]; // [1, 2, 3, 4].
main() => print(another);

However this fails to compile with the error:

$dart example/dart.dart
example/example.dart:4:21: Error: '...' is not supported in constant expressions.
const another = [1, ...list, 4]; // [1, 2, 3, 4].
                    ^^^

Version information:

  • Dart VM version: 2.4.0 (Wed Jun 19 11:53:45 2019 +0200) on "windows_x64"
  • IntelliJ IDEA 2019.2 (Ultimate Edition) Build #IU-192.5728.98

This annotation processor is my use case. I’d like to split the queries parameter into maps defined in different files. For example:

// In queries/todos.dart
const todoQueries = {
  'getTodos': 'SELECT * FROM todo'
};

// In database.dart
@UseMoor(
  queries: {
    'getUsers': 'SELECT * FROM user',
    ...todoQueries,
  },
)
class TodoDb extends _$TodoDb {

Interestingly, pub run build_runner build runs without issue and the annotation processor spreads the todoQueries as expected, even though the analyzer has underlined it:

idea64_2019-07-29_23-06-51

Author: Fantashit

1 thought on “Spread operator in const collection literals

  1. UI-as-code features were only supported in non-const contexts. CHANGELOG has the following note:

    Note: These features are not currently supported in const collection literals. In a future release, we intend to relax this restriction and allow spread and collection if inside const collections.

    In fact 2.5 release will actually fully enable it. This already works on master HEAD:

    ╭─~/s/d/sdk ⟨master …5⟩
    ╰─» cat /tmp/x.dart
    const list = [2, 3];
    const another = [1, ...list, 4]; // [1, 2, 3, 4].
    main() => print(another);
    ╭─~/s/d/sdk ⟨master …5⟩
    ╰─» out/ReleaseX64/dart --version
    Dart VM version: 2.5.0-edge.6ebaa7c5877030e42a8c1b8d1297f0d161571d4a (Tue Jul 30 05:15:02 2019 +0000) on "linux_x64"
    ╭─~/s/d/sdk ⟨master …5⟩ ⟨1m37s957ms⟩
    ╰─» out/ReleaseX64/dart /tmp/x.dart
    [1, 2, 3, 4]

Comments are closed.