├── isolates ├── json_01.json ├── .gitignore ├── json_02.json ├── analysis_options.yaml ├── json_03.json ├── mono_pkg.yaml ├── pubspec.yaml ├── README.md └── bin │ ├── send_and_receive.dart │ └── long_running_isolate.dart ├── ffi ├── hello_world │ ├── .dockerignore │ ├── analysis_options.yaml │ ├── setup.sh │ ├── hello_library │ │ ├── hello.def │ │ ├── hello.h │ │ ├── .gitignore │ │ ├── CMakeLists.txt │ │ └── hello.c │ ├── mono_pkg.yaml │ ├── pubspec.yaml │ ├── test │ │ └── hello_world_test.dart │ └── hello.dart ├── structs │ ├── analysis_options.yaml │ ├── structs_library │ │ ├── structs.def │ │ ├── CMakeLists.txt │ │ ├── structs.h │ │ └── structs.c │ ├── mono_pkg.yaml │ ├── pubspec.yaml │ ├── test │ │ └── structs_test.dart │ └── structs.dart ├── primitives │ ├── analysis_options.yaml │ ├── primitives_library │ │ ├── primitives.def │ │ ├── primitives.h │ │ ├── CMakeLists.txt │ │ └── primitives.c │ ├── mono_pkg.yaml │ ├── pubspec.yaml │ ├── test │ │ └── primitives_test.dart │ └── primitives.dart ├── test_utils │ ├── analysis_options.yaml │ ├── mono_pkg.yaml │ ├── pubspec.yaml │ └── lib │ │ └── test_utils.dart ├── system_command │ ├── analysis_options.yaml │ ├── mono_pkg.yaml │ ├── pubspec.yaml │ ├── README.md │ ├── linux.dart │ ├── macos.dart │ ├── windows.dart │ └── win32ui.dart ├── .gitignore └── README.md ├── command_line ├── analysis_options.yaml ├── .gitignore ├── mono_pkg.yaml ├── pubspec.yaml ├── README.md ├── lib │ ├── src │ │ ├── util.dart │ │ ├── options.dart │ │ ├── formatter.dart │ │ └── options.g.dart │ └── github_activity.dart ├── test │ └── github_stats_test.dart └── bin │ └── github_activity.dart ├── native_app ├── .gitignore ├── analysis_options.yaml ├── bin │ └── main.dart ├── mono_pkg.yaml ├── pubspec.yaml └── README.md ├── enhanced_enums ├── .gitignore ├── analysis_options.yaml ├── mono_pkg.yaml ├── pubspec.yaml ├── lib │ ├── plain.dart │ ├── typed_enum.dart │ ├── comparable.dart │ ├── comparable_mixin.dart │ ├── members.dart │ └── complete_example.dart ├── test │ ├── typed_enum_test.dart │ ├── members_test.dart │ ├── comparable_test.dart │ ├── comparable_mixin_test.dart │ ├── plain_test.dart │ └── complete_example_test.dart └── README.md ├── extension_methods ├── analysis_options.yaml ├── .gitignore ├── mono_pkg.yaml ├── pubspec.yaml ├── test │ └── first_char_test.dart ├── example │ ├── generics.dart │ ├── json_helpers.dart │ ├── privacy_destination.dart │ ├── code_generation.dart │ ├── getter_extensions.dart │ ├── fluid_api.dart │ ├── operator_extensions.dart │ └── core_type_extensions.dart ├── lib │ ├── privacy_source.dart │ └── some_api.dart └── README.md ├── server ├── google_apis │ ├── analysis_options.yaml │ ├── .gitignore │ ├── mono_pkg.yaml │ ├── pubspec.yaml │ ├── Dockerfile │ ├── README.md │ └── bin │ │ └── server.dart ├── simple │ ├── public │ │ ├── 64.png │ │ ├── dashland.jpeg │ │ └── index.html │ ├── .gitignore │ ├── dart_test.yaml │ ├── analysis_options.yaml │ ├── mono_pkg.yaml │ ├── pubspec.yaml │ ├── tool │ │ └── docker_test_script.sh │ ├── test │ │ ├── docker_test.dart │ │ ├── server_test.dart │ │ └── test_definitions.dart │ ├── README.md │ ├── Dockerfile │ └── bin │ │ └── server.dart └── README.md ├── null_safety └── calculate_lix │ ├── analysis_options.yaml │ ├── mono_pkg.yaml │ ├── CHANGELOG.md │ ├── .gitignore │ ├── pubspec.yaml │ ├── text │ └── lorem-ipsum.txt │ ├── README.md │ ├── bin │ └── main.dart │ ├── LICENSE │ └── lib │ └── lix.dart ├── .gitignore ├── parameters ├── analysis_options.yaml ├── mono_pkg.yaml ├── .gitignore ├── pubspec.yaml ├── README.md ├── lib │ ├── named_parameters.dart │ └── super_initalizer.dart └── test │ ├── super_initializer_test.dart │ └── named_parameters_test.dart ├── package_constraint_solver ├── .gitignore ├── mono_pkg.yaml ├── CHANGELOG.md ├── pubspec.yaml ├── analysis_options.yaml ├── LICENSE ├── example │ ├── example.dart │ └── scheduler_example.dart ├── test │ └── constraint_solver_test.dart ├── README.md └── lib │ └── constraint_solver.dart ├── AUTHORS ├── mono_repo.yaml ├── .github ├── dependabot.yml └── workflows │ └── container_docker_test.yml ├── LICENSE ├── README.md ├── CONTRIBUTING.md └── tool └── ci.sh /isolates/json_01.json: -------------------------------------------------------------------------------- 1 | { 2 | "a": "foo" 3 | } -------------------------------------------------------------------------------- /ffi/hello_world/.dockerignore: -------------------------------------------------------------------------------- 1 | hello_library/CMakeCache.txt 2 | -------------------------------------------------------------------------------- /isolates/.gitignore: -------------------------------------------------------------------------------- 1 | .dart_tool/ 2 | build/ 3 | pubspec.lock 4 | -------------------------------------------------------------------------------- /isolates/json_02.json: -------------------------------------------------------------------------------- 1 | { 2 | "a": "foo", 3 | "b": "bar" 4 | } -------------------------------------------------------------------------------- /command_line/analysis_options.yaml: -------------------------------------------------------------------------------- 1 | include: package:lints/recommended.yaml 2 | -------------------------------------------------------------------------------- /ffi/structs/analysis_options.yaml: -------------------------------------------------------------------------------- 1 | include: package:lints/recommended.yaml 2 | -------------------------------------------------------------------------------- /isolates/analysis_options.yaml: -------------------------------------------------------------------------------- 1 | include: package:lints/recommended.yaml 2 | -------------------------------------------------------------------------------- /native_app/.gitignore: -------------------------------------------------------------------------------- 1 | .dart_tool/ 2 | pubspec.lock 3 | build/ 4 | doc/api/ 5 | -------------------------------------------------------------------------------- /native_app/analysis_options.yaml: -------------------------------------------------------------------------------- 1 | include: package:lints/recommended.yaml 2 | -------------------------------------------------------------------------------- /native_app/bin/main.dart: -------------------------------------------------------------------------------- 1 | void main() { 2 | print('Hello, World!'); 3 | } 4 | -------------------------------------------------------------------------------- /command_line/.gitignore: -------------------------------------------------------------------------------- 1 | .dart_tool/ 2 | pubspec.lock 3 | build/ 4 | doc/api/ 5 | -------------------------------------------------------------------------------- /enhanced_enums/.gitignore: -------------------------------------------------------------------------------- 1 | .dart_tool/ 2 | pubspec.lock 3 | build/ 4 | doc/api/ 5 | -------------------------------------------------------------------------------- /enhanced_enums/analysis_options.yaml: -------------------------------------------------------------------------------- 1 | include: package:lints/recommended.yaml 2 | -------------------------------------------------------------------------------- /extension_methods/analysis_options.yaml: -------------------------------------------------------------------------------- 1 | include: package:lints/recommended.yaml 2 | -------------------------------------------------------------------------------- /ffi/hello_world/analysis_options.yaml: -------------------------------------------------------------------------------- 1 | include: package:lints/recommended.yaml 2 | -------------------------------------------------------------------------------- /ffi/primitives/analysis_options.yaml: -------------------------------------------------------------------------------- 1 | include: package:lints/recommended.yaml 2 | -------------------------------------------------------------------------------- /ffi/test_utils/analysis_options.yaml: -------------------------------------------------------------------------------- 1 | include: package:lints/recommended.yaml 2 | -------------------------------------------------------------------------------- /isolates/json_03.json: -------------------------------------------------------------------------------- 1 | { 2 | "a": "foo", 3 | "b": "bar", 4 | "c": "bar" 5 | } -------------------------------------------------------------------------------- /ffi/hello_world/setup.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | export DYLD_LIBRARY_PATH=.:$DYLD_LIBRARY_PATH -------------------------------------------------------------------------------- /server/google_apis/analysis_options.yaml: -------------------------------------------------------------------------------- 1 | include: package:lints/recommended.yaml 2 | -------------------------------------------------------------------------------- /ffi/hello_world/hello_library/hello.def: -------------------------------------------------------------------------------- 1 | LIBRARY hello 2 | EXPORTS 3 | hello_world 4 | -------------------------------------------------------------------------------- /null_safety/calculate_lix/analysis_options.yaml: -------------------------------------------------------------------------------- 1 | include: package:lints/recommended.yaml 2 | -------------------------------------------------------------------------------- /extension_methods/.gitignore: -------------------------------------------------------------------------------- 1 | .dart_tool/ 2 | pubspec.lock 3 | build/ 4 | doc/api/ 5 | .idea/ 6 | -------------------------------------------------------------------------------- /server/simple/public/64.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dart-lang/samples/HEAD/server/simple/public/64.png -------------------------------------------------------------------------------- /server/simple/.gitignore: -------------------------------------------------------------------------------- 1 | # https://dart.dev/guides/libraries/private-files 2 | .dart_tool/ 3 | pubspec.lock 4 | -------------------------------------------------------------------------------- /server/simple/dart_test.yaml: -------------------------------------------------------------------------------- 1 | tags: 2 | presubmit-only: 3 | skip: "Should only be run during presubmit" 4 | -------------------------------------------------------------------------------- /ffi/primitives/primitives_library/primitives.def: -------------------------------------------------------------------------------- 1 | LIBRARY structs 2 | EXPORTS 3 | sum 4 | subtract 5 | multiply -------------------------------------------------------------------------------- /server/simple/public/dashland.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dart-lang/samples/HEAD/server/simple/public/dashland.jpeg -------------------------------------------------------------------------------- /server/google_apis/.gitignore: -------------------------------------------------------------------------------- 1 | # https://dart.dev/guides/libraries/private-files 2 | .dart_tool/ 3 | build/ 4 | pubspec.lock 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Ignoring pub generated files. 2 | **/package_config.json 3 | 4 | # Ignore system and IDE files 5 | .idea 6 | .DS_STORE 7 | -------------------------------------------------------------------------------- /parameters/analysis_options.yaml: -------------------------------------------------------------------------------- 1 | include: package:lints/recommended.yaml 2 | 3 | linter: 4 | rules: 5 | - use_super_parameters 6 | -------------------------------------------------------------------------------- /isolates/mono_pkg.yaml: -------------------------------------------------------------------------------- 1 | sdk: 2 | - stable 3 | - dev 4 | 5 | stages: 6 | - analysis: 7 | - analyze: --fatal-infos . 8 | - format 9 | -------------------------------------------------------------------------------- /native_app/mono_pkg.yaml: -------------------------------------------------------------------------------- 1 | sdk: 2 | - stable 3 | - dev 4 | 5 | stages: 6 | - analysis: 7 | - analyze: --fatal-infos . 8 | - format 9 | -------------------------------------------------------------------------------- /parameters/mono_pkg.yaml: -------------------------------------------------------------------------------- 1 | sdk: 2 | - stable 3 | - dev 4 | 5 | stages: 6 | - analysis: 7 | - analyze: --fatal-infos . 8 | - format 9 | -------------------------------------------------------------------------------- /ffi/test_utils/mono_pkg.yaml: -------------------------------------------------------------------------------- 1 | sdk: 2 | - stable 3 | - dev 4 | 5 | stages: 6 | - analysis: 7 | - analyze: --fatal-infos . 8 | - format 9 | -------------------------------------------------------------------------------- /ffi/system_command/analysis_options.yaml: -------------------------------------------------------------------------------- 1 | include: package:lints/recommended.yaml 2 | 3 | linter: 4 | rules: 5 | constant_identifier_names: false 6 | -------------------------------------------------------------------------------- /ffi/system_command/mono_pkg.yaml: -------------------------------------------------------------------------------- 1 | sdk: 2 | - stable 3 | - dev 4 | 5 | stages: 6 | - analysis: 7 | - analyze: --fatal-infos . 8 | - format 9 | -------------------------------------------------------------------------------- /null_safety/calculate_lix/mono_pkg.yaml: -------------------------------------------------------------------------------- 1 | sdk: 2 | - stable 3 | - dev 4 | 5 | stages: 6 | - analysis: 7 | - analyze: --fatal-infos . 8 | - format 9 | -------------------------------------------------------------------------------- /parameters/.gitignore: -------------------------------------------------------------------------------- 1 | # Files and directories created by pub. 2 | .dart_tool/ 3 | 4 | # Conventional directory for build output. 5 | build/ 6 | 7 | pubspec.lock 8 | -------------------------------------------------------------------------------- /ffi/structs/structs_library/structs.def: -------------------------------------------------------------------------------- 1 | LIBRARY structs 2 | EXPORTS 3 | hello_world 4 | create_place 5 | create_coordinate 6 | reverse 7 | distance 8 | 9 | -------------------------------------------------------------------------------- /package_constraint_solver/.gitignore: -------------------------------------------------------------------------------- 1 | # Files and directories created by pub. 2 | .dart_tool/ 3 | 4 | # Conventional directory for build output. 5 | build/ 6 | 7 | pubspec.lock 8 | -------------------------------------------------------------------------------- /server/simple/analysis_options.yaml: -------------------------------------------------------------------------------- 1 | include: package:lints/recommended.yaml 2 | 3 | linter: 4 | rules: 5 | - prefer_const_constructors 6 | - prefer_expression_function_bodies 7 | -------------------------------------------------------------------------------- /command_line/mono_pkg.yaml: -------------------------------------------------------------------------------- 1 | sdk: 2 | - stable 3 | - dev 4 | 5 | stages: 6 | - analysis: 7 | - analyze: --fatal-infos . 8 | - format 9 | - unit_test: 10 | - test 11 | -------------------------------------------------------------------------------- /enhanced_enums/mono_pkg.yaml: -------------------------------------------------------------------------------- 1 | sdk: 2 | - stable 3 | - dev 4 | 5 | stages: 6 | - analysis: 7 | - analyze: --fatal-infos . 8 | - format 9 | - unit_test: 10 | - test 11 | -------------------------------------------------------------------------------- /ffi/hello_world/mono_pkg.yaml: -------------------------------------------------------------------------------- 1 | sdk: 2 | - stable 3 | - dev 4 | 5 | stages: 6 | - analysis: 7 | - analyze: --fatal-infos . 8 | - format 9 | - unit_test: 10 | - test: 11 | -------------------------------------------------------------------------------- /ffi/primitives/mono_pkg.yaml: -------------------------------------------------------------------------------- 1 | sdk: 2 | - stable 3 | - dev 4 | 5 | stages: 6 | - analysis: 7 | - analyze: --fatal-infos . 8 | - format 9 | - unit_test: 10 | - test: 11 | -------------------------------------------------------------------------------- /ffi/structs/mono_pkg.yaml: -------------------------------------------------------------------------------- 1 | sdk: 2 | - stable 3 | - dev 4 | 5 | stages: 6 | - analysis: 7 | - analyze: --fatal-infos . 8 | - format 9 | - unit_test: 10 | - test: 11 | -------------------------------------------------------------------------------- /server/simple/mono_pkg.yaml: -------------------------------------------------------------------------------- 1 | sdk: 2 | - stable 3 | - dev 4 | 5 | stages: 6 | - analysis: 7 | - analyze: --fatal-infos . 8 | - format 9 | - unit_test: 10 | - test 11 | -------------------------------------------------------------------------------- /extension_methods/mono_pkg.yaml: -------------------------------------------------------------------------------- 1 | sdk: 2 | - stable 3 | - dev 4 | 5 | stages: 6 | - analysis: 7 | - analyze: --fatal-infos . 8 | - format 9 | - unit_test: 10 | - test 11 | -------------------------------------------------------------------------------- /package_constraint_solver/mono_pkg.yaml: -------------------------------------------------------------------------------- 1 | sdk: 2 | - dev 3 | 4 | stages: 5 | - analysis: 6 | - analyze: --fatal-infos . 7 | - format 8 | - unit_test: 9 | - test_with_coverage 10 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | # Below is a list of people and organizations that have contributed 2 | # to the Dart project. Names should be added to the list like so: 3 | # 4 | # Name/Organization 5 | 6 | Google LLC 7 | -------------------------------------------------------------------------------- /null_safety/calculate_lix/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 1.1.0 2 | 3 | - Roll to use Dart 2.10 dev-channel SDK 4 | - Change `collection` dependency from git to pub.dev pre-release version 5 | 6 | ## 1.0.0 7 | 8 | - Initial version 9 | -------------------------------------------------------------------------------- /package_constraint_solver/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 1.0.0 2 | 3 | - Release version 1.0.0 4 | 5 | ## 1.0.0-pre.2 6 | 7 | - Add pub.dev badge to README 8 | 9 | ## 1.0.0-pre.1 10 | 11 | - Update README 12 | 13 | ## 1.0.0-pre.0 14 | 15 | - Initial version. 16 | -------------------------------------------------------------------------------- /ffi/test_utils/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: test_utils 2 | 3 | # This example isn't intended for publishing on pub.dev. 4 | publish_to: none 5 | 6 | environment: 7 | sdk: ^3.10.0 8 | 9 | dependencies: 10 | path: ^1.9.1 11 | 12 | dev_dependencies: 13 | lints: ^6.0.0 14 | -------------------------------------------------------------------------------- /isolates/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: isolates 2 | description: A sample command-line application. 3 | publish_to: none 4 | 5 | environment: 6 | sdk: ^3.10.0 7 | 8 | dependencies: 9 | async: ^2.13.0 10 | 11 | dev_dependencies: 12 | lints: ^6.0.0 13 | test: ^1.27.0 14 | -------------------------------------------------------------------------------- /parameters/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: parameters 2 | description: Function parameters and super initializers examples 3 | version: 1.0.0 4 | 5 | publish_to: none 6 | 7 | environment: 8 | sdk: ^3.10.0 9 | 10 | dev_dependencies: 11 | lints: ^6.0.0 12 | test: ^1.27.0 13 | -------------------------------------------------------------------------------- /server/google_apis/mono_pkg.yaml: -------------------------------------------------------------------------------- 1 | sdk: 2 | - stable 3 | - dev 4 | 5 | stages: 6 | - analysis: 7 | - analyze: --fatal-infos . 8 | - format 9 | # This sample uses a live Google API, so no unit tests are provided – yet 10 | # - unit_test: 11 | # - test 12 | -------------------------------------------------------------------------------- /ffi/hello_world/hello_library/hello.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | void hello_world(); -------------------------------------------------------------------------------- /null_safety/calculate_lix/.gitignore: -------------------------------------------------------------------------------- 1 | pubspec.lock 2 | 3 | # Files and directories used by the Dart SDK 4 | .dart_tool/ 5 | build/ 6 | doc/api/ 7 | 8 | # Android Studio configuration 9 | .idea/ 10 | !.idea/runConfigurations/Run_main_with_test_data.xml 11 | 12 | # VSCode configuration 13 | .vscode/settings.json 14 | -------------------------------------------------------------------------------- /enhanced_enums/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: enhanced_enums 2 | description: Samples that demonstrates the enhanced enums syntax 3 | 4 | # This example isn't intended for publishing on pub.dev. 5 | publish_to: none 6 | 7 | environment: 8 | sdk: ^3.10.0 9 | 10 | dev_dependencies: 11 | lints: ^6.0.0 12 | test: ^1.27.0 13 | -------------------------------------------------------------------------------- /server/README.md: -------------------------------------------------------------------------------- 1 | Each sample: 2 | 3 | 1. Uses [package:shelf](https://pub.dev/packages/shelf) to make the server logic 4 | readable and composable. 5 | 1. Includes a `Dockerfile` to make hosting easy. 6 | 1. Can be deployed to [Cloud Run](https://cloud.google.com/run). 7 | 8 | See the `README.md` in each directory for details. 9 | -------------------------------------------------------------------------------- /extension_methods/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: extension_methods 2 | description: >- 3 | A set of use cases for the extension methods feature. 4 | 5 | # This example isn't intended for publishing on pub.dev. 6 | publish_to: none 7 | 8 | environment: 9 | sdk: ^3.10.0 10 | 11 | dev_dependencies: 12 | lints: ^6.0.0 13 | test: ^1.27.0 14 | -------------------------------------------------------------------------------- /enhanced_enums/lib/plain.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Plain enum. 6 | /// 7 | /// This enum doesn't use any of enhancements. 8 | enum Plain { foo, bar, baz } 9 | -------------------------------------------------------------------------------- /ffi/.gitignore: -------------------------------------------------------------------------------- 1 | *.o 2 | *.dylib 3 | a.out 4 | .vscode/ 5 | .dart_tool 6 | sdk-version 7 | *snapshot* 8 | pubspec.lock 9 | CMakeCache.txt 10 | CMakeFiles 11 | cmake_install.cmake 12 | Makefile 13 | primitives/primitives_library/primitives_test 14 | structs/structs_library/structs_test 15 | 16 | # Windows 17 | *.obj 18 | *.dll 19 | *.lib 20 | *.exe 21 | *.exp 22 | -------------------------------------------------------------------------------- /ffi/primitives/primitives_library/primitives.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | int sum(int a, int b); 6 | int subtract(int *a, int b); 7 | int *multiply(int a, int b); 8 | -------------------------------------------------------------------------------- /ffi/system_command/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: system_command 2 | description: A FFI application that invokes system commands. 3 | 4 | # This example isn't intended for publishing on pub.dev. 5 | publish_to: none 6 | 7 | environment: 8 | sdk: ^3.10.0 9 | 10 | dependencies: 11 | ffi: ^2.1.4 12 | 13 | dev_dependencies: 14 | lints: ^6.0.0 15 | test: ^1.27.0 16 | -------------------------------------------------------------------------------- /server/google_apis/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: cloud_run_google_apis 2 | publish_to: none # not intended for publication to pub.dev 3 | 4 | environment: 5 | sdk: ^3.10.0 6 | 7 | dependencies: 8 | google_cloud: ^0.2.0 9 | googleapis: ^15.0.0 10 | googleapis_auth: ^2.0.0 11 | shelf: ^1.4.2 12 | shelf_router: ^1.1.4 13 | 14 | dev_dependencies: 15 | lints: ^6.0.0 16 | -------------------------------------------------------------------------------- /server/simple/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: container_server_example 2 | publish_to: none # not intended for publication to pub.dev 3 | 4 | environment: 5 | sdk: ^3.10.0 6 | 7 | dependencies: 8 | shelf: ^1.4.2 9 | shelf_router: ^1.1.4 10 | shelf_static: ^1.1.3 11 | 12 | dev_dependencies: 13 | http: ^1.6.0 14 | lints: ^6.0.0 15 | test: ^1.27.0 16 | test_process: ^2.1.1 17 | -------------------------------------------------------------------------------- /mono_repo.yaml: -------------------------------------------------------------------------------- 1 | # Run `mono_repo generate --validate` to check 2 | # that everything is up to date 3 | self_validate: true 4 | github: 5 | on: 6 | push: 7 | branches: 8 | - main 9 | pull_request: 10 | 11 | # Merges all analyze stages into one bot, which is more efficient 12 | merge_stages: 13 | - analysis 14 | 15 | coverage_service: 16 | - coveralls 17 | -------------------------------------------------------------------------------- /native_app/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: native_app 2 | description: >- 3 | A command line application that can be compiled to native code using 4 | dart compile exe. 5 | 6 | # This example isn't intended for publishing on pub.dev. 7 | publish_to: none 8 | 9 | environment: 10 | sdk: ^3.10.0 11 | 12 | dev_dependencies: 13 | lints: ^6.0.0 14 | 15 | executables: 16 | main: hello_world 17 | -------------------------------------------------------------------------------- /null_safety/calculate_lix/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: calculate_lix 2 | description: A command-line application demonstrating use of null safety. 3 | version: 1.3.0 4 | 5 | # This example isn't intended for publishing on pub.dev. 6 | publish_to: none 7 | 8 | environment: 9 | sdk: ^3.10.0 10 | 11 | dependencies: 12 | collection: ^1.19.1 13 | 14 | dev_dependencies: 15 | lints: ^6.0.0 16 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # Dependabot configuration file. 2 | # See https://docs.github.com/en/code-security/dependabot/dependabot-version-updates 3 | version: 2 4 | 5 | updates: 6 | - package-ecosystem: github-actions 7 | directory: / 8 | schedule: 9 | interval: monthly 10 | labels: 11 | - autosubmit 12 | groups: 13 | github-actions: 14 | patterns: 15 | - "*" 16 | -------------------------------------------------------------------------------- /package_constraint_solver/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: constraint_solver 2 | description: A general-purpose backtracking constraint satisfaction algorithm. 3 | repository: https://github.com/dart-lang/samples/tree/main/package_constraint_solver 4 | publish_to: none 5 | 6 | environment: 7 | sdk: ^3.10.0 8 | 9 | dependencies: 10 | path: ^1.9.1 11 | 12 | dev_dependencies: 13 | checks: ^0.3.1 14 | lints: ^6.0.0 15 | intl: ^0.20.2 16 | test: ^1.27.0 17 | -------------------------------------------------------------------------------- /server/simple/tool/docker_test_script.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | 5 | image="$(docker build -q .)" 6 | echo Image created: "$image" 7 | container=$(docker run -d -p 8080:8080 --rm "$image") 8 | echo Container started: "$container" 9 | sleep 1 10 | dart run test test/docker_test.dart -t presubmit-only --run-skipped || EXIT_CODE=$? 11 | echo Container killed "$(docker kill "$container")" 12 | echo Image deleted "$(docker rmi "$image")" 13 | exit ${EXIT_CODE} 14 | -------------------------------------------------------------------------------- /ffi/hello_world/hello_library/.gitignore: -------------------------------------------------------------------------------- 1 | # CMake generated files and directories 2 | CMakeCache.txt 3 | CMakeFiles/ 4 | CmakeScripts/ 5 | Makefile 6 | cmake_install.cmake 7 | 8 | # Xcode tooling generated via `cmake -G Xcode .` 9 | hello_library.xcodeproj/ 10 | 11 | # Xcode generated build and output directories 12 | hello_library.build/ 13 | 14 | # Generated test binary 15 | hello_test 16 | 17 | # Generated shared library files 18 | *.dylib 19 | *.so 20 | *.so.* 21 | *.dll 22 | -------------------------------------------------------------------------------- /ffi/hello_world/hello_library/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.7 FATAL_ERROR) 2 | project(hello_library VERSION 1.0.0 LANGUAGES C) 3 | add_library(hello_library SHARED hello.c hello.def) 4 | add_executable(hello_test hello.c) 5 | 6 | set_target_properties(hello_library PROPERTIES 7 | PUBLIC_HEADER hello.h 8 | VERSION ${PROJECT_VERSION} 9 | SOVERSION 1 10 | OUTPUT_NAME "hello" 11 | XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "Hex_Identity_ID_Goes_Here" 12 | ) 13 | -------------------------------------------------------------------------------- /extension_methods/test/first_char_test.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'package:extension_methods/privacy_source.dart'; 6 | import 'package:test/test.dart'; 7 | 8 | void main() { 9 | test('String.firstChar extension works', () { 10 | expect('Dash'.firstChar, 'D'); 11 | }); 12 | } 13 | -------------------------------------------------------------------------------- /ffi/primitives/primitives_library/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.7 FATAL_ERROR) 2 | project(primitives_library VERSION 1.0.0 LANGUAGES C) 3 | add_library(primitives_library SHARED primitives.c primitives.def) 4 | add_executable(primitives_test primitives.c) 5 | 6 | set_target_properties(primitives_library PROPERTIES 7 | PUBLIC_HEADER primitives.h 8 | VERSION ${PROJECT_VERSION} 9 | SOVERSION 1 10 | OUTPUT_NAME "primitives" 11 | XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "Hex_Identity_ID_Goes_Here" 12 | ) 13 | -------------------------------------------------------------------------------- /enhanced_enums/test/typed_enum_test.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'package:enhanced_enums/typed_enum.dart'; 6 | import 'package:test/test.dart'; 7 | 8 | void main() { 9 | test('Use typed enum', () { 10 | expect(EnumWithType.numbers.items, [1, 2, 3]); 11 | expect(EnumWithType.strings.items, ['A', 'B', 'C']); 12 | }); 13 | } 14 | -------------------------------------------------------------------------------- /enhanced_enums/lib/typed_enum.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Enum with a generic type. 6 | /// 7 | /// The type [T] is used to define the type of [List] the enum contains. 8 | enum EnumWithType { 9 | numbers([1, 2, 3]), 10 | strings(['A', 'B', 'C']); 11 | 12 | final List items; 13 | 14 | const EnumWithType(this.items); 15 | } 16 | -------------------------------------------------------------------------------- /enhanced_enums/lib/comparable.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Enum that implements a Comparable 6 | enum Ordering implements Comparable { 7 | zero(0), 8 | one(1), 9 | many(99); 10 | 11 | final int quantity; 12 | 13 | const Ordering(this.quantity); 14 | 15 | @override 16 | int compareTo(Ordering other) => quantity - other.quantity; 17 | } 18 | -------------------------------------------------------------------------------- /command_line/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: cli_app 2 | description: >- 3 | A command line application that can be compiled to native code using 4 | dart compile exe. 5 | 6 | # This example isn't intended for publishing on pub.dev. 7 | publish_to: none 8 | 9 | environment: 10 | sdk: ^3.10.0 11 | 12 | dependencies: 13 | args: ^2.7.0 14 | build_cli_annotations: ^2.1.1 15 | github: ^9.25.0 16 | intl: ^0.20.2 17 | 18 | dev_dependencies: 19 | build_cli: ^2.2.8 20 | build_runner: ^2.10.3 21 | lints: ^6.0.0 22 | test: ^1.27.0 23 | 24 | executables: 25 | github_activity: github_activity 26 | -------------------------------------------------------------------------------- /ffi/structs/structs_library/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.7 FATAL_ERROR) 2 | project(structs_library VERSION 1.0.0 LANGUAGES C) 3 | add_library(structs_library SHARED structs.c structs.def) 4 | target_link_libraries(structs_library PUBLIC m) 5 | add_executable(structs_test structs.c) 6 | target_link_libraries(structs_test PUBLIC m) 7 | 8 | set_target_properties(structs_library PROPERTIES 9 | PUBLIC_HEADER structs.h 10 | VERSION ${PROJECT_VERSION} 11 | SOVERSION 1 12 | OUTPUT_NAME "structs" 13 | XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "Hex_Identity_ID_Goes_Here" 14 | ) 15 | -------------------------------------------------------------------------------- /enhanced_enums/lib/comparable_mixin.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Enum that implements a Comparable using a mixin 6 | enum Ordering with EnumIndexOrdering { zero, few, many } 7 | 8 | /// Mixin that uses the enum index to create a comparable 9 | mixin EnumIndexOrdering on Enum implements Comparable { 10 | @override 11 | int compareTo(T other) => index - other.index; 12 | } 13 | -------------------------------------------------------------------------------- /enhanced_enums/test/members_test.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'package:enhanced_enums/members.dart'; 6 | import 'package:test/test.dart'; 7 | 8 | void main() { 9 | test('Enum with members to String', () { 10 | expect(LogPriority.warning.toString(), 'Warning(2)'); 11 | expect(LogPriority.error.toString(), 'Error(1)'); 12 | expect(LogPriority.log.toString(), 'Log(-1)'); 13 | }); 14 | } 15 | -------------------------------------------------------------------------------- /parameters/README.md: -------------------------------------------------------------------------------- 1 | # Function parameters and super-initializer samples 2 | 3 | This sample demonstrates Dart's function parameters capabilities, 4 | including named parameters, optional parameters, and the ability to have named 5 | arguments anywhere in the argument list. 6 | 7 | As well, the sample demonstrates super-initializer parameters. 8 | 9 | These features are part of Dart 2.17. The programs in this folder won't 10 | compile in earlier versions. 11 | 12 | ## Instructions 13 | 14 | Read the source code in the `lib/` directory. The code is split into 15 | separate files according to topics or use cases. 16 | -------------------------------------------------------------------------------- /ffi/hello_world/hello_library/hello.c: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | #include 6 | #include "hello.h" 7 | 8 | int main() 9 | { 10 | hello_world(); 11 | return 0; 12 | } 13 | 14 | // Note: 15 | // ---only on Windows--- 16 | // Every function needs to be exported to be able to access the functions by dart. 17 | // Refer: https://stackoverflow.com/q/225432/8608146 18 | void hello_world() 19 | { 20 | printf("Hello World\n"); 21 | } -------------------------------------------------------------------------------- /ffi/primitives/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: primitives_ffi 2 | description: A super simple example of calling C code from Dart with FFI 3 | 4 | # This example isn't intended for publishing on pub.dev. 5 | publish_to: none 6 | 7 | environment: 8 | sdk: ^3.10.0 9 | 10 | dependencies: 11 | ffi: ^2.1.4 12 | path: ^1.9.1 13 | 14 | dev_dependencies: 15 | lints: ^6.0.0 16 | test: ^1.27.0 17 | # test_utils depends on code elsewhere in the samples repository. 18 | # You can reference it for useful cross-platform testing functionality 19 | # or remove it if you want to use this example standalone. 20 | test_utils: 21 | path: ../test_utils 22 | -------------------------------------------------------------------------------- /ffi/hello_world/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: hello_world_ffi 2 | version: 0.0.1 3 | description: >- 4 | A super simple example of calling C code from Dart with FFI 5 | 6 | # This example isn't intended for publishing on pub.dev. 7 | publish_to: none 8 | 9 | environment: 10 | sdk: ^3.10.0 11 | 12 | dependencies: 13 | path: ^1.9.1 14 | 15 | dev_dependencies: 16 | lints: ^6.0.0 17 | test: ^1.27.0 18 | # test_utils depends on code elsewhere in the samples repository. 19 | # You can reference it for useful cross-platform testing functionality 20 | # or remove it if you want to use this example standalone. 21 | test_utils: 22 | path: ../test_utils 23 | -------------------------------------------------------------------------------- /ffi/structs/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: structs_ffi 2 | version: 0.0.1 3 | description: >- 4 | A super simple example of calling C code from Dart with FFI using structs 5 | 6 | # This example isn't intended for publishing on pub.dev. 7 | publish_to: none 8 | 9 | environment: 10 | sdk: ^3.10.0 11 | 12 | dependencies: 13 | ffi: ^2.1.4 14 | path: ^1.9.1 15 | 16 | dev_dependencies: 17 | lints: ^6.0.0 18 | test: ^1.27.0 19 | # test_utils depends on code elsewhere in the samples repository. 20 | # You can reference it for useful cross-platform testing functionality 21 | # or remove it if you want to use this example standalone. 22 | test_utils: 23 | path: ../test_utils 24 | -------------------------------------------------------------------------------- /enhanced_enums/test/comparable_test.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'package:enhanced_enums/comparable.dart'; 6 | import 'package:test/test.dart'; 7 | 8 | void main() { 9 | test('Sort Quantity enum using compareTo', () { 10 | // unsorted list 11 | final list = [Ordering.many, Ordering.zero, Ordering.one]; 12 | 13 | // sort using compareTo 14 | list.sort(); 15 | 16 | // list is sorted by amount 17 | expect(list, [Ordering.zero, Ordering.one, Ordering.many]); 18 | }); 19 | } 20 | -------------------------------------------------------------------------------- /server/simple/test/docker_test.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | @Tags(['presubmit-only']) 6 | library; 7 | 8 | import 'package:test/test.dart'; 9 | 10 | import 'test_definitions.dart'; 11 | 12 | void main() { 13 | void testServer(String name, Future Function(String host) func) { 14 | test(name, () async { 15 | await func('http://localhost:8080'); 16 | }, timeout: _defaultTimeout); 17 | } 18 | 19 | runTests(testServer); 20 | } 21 | 22 | const _defaultTimeout = Timeout(Duration(seconds: 3)); 23 | -------------------------------------------------------------------------------- /enhanced_enums/test/comparable_mixin_test.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'package:enhanced_enums/comparable_mixin.dart'; 6 | import 'package:test/test.dart'; 7 | 8 | void main() { 9 | test('Sort enum using compareTo in mixin', () { 10 | // unsorted list 11 | final list = [Ordering.many, Ordering.zero, Ordering.few]; 12 | 13 | // sort using compareTo 14 | list.sort(); 15 | 16 | // list is sorted by amount 17 | expect(list, [Ordering.zero, Ordering.few, Ordering.many]); 18 | }); 19 | } 20 | -------------------------------------------------------------------------------- /enhanced_enums/lib/members.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Enum with members and named constructor. 6 | /// 7 | /// Also shows an example of [toString] override. 8 | enum LogPriority { 9 | warning(2, "Warning"), 10 | error(1, "Error"), 11 | log.unknown("Log"); 12 | 13 | const LogPriority(this.priority, this.prefix); 14 | const LogPriority.unknown(String prefix) : this(-1, prefix); 15 | 16 | final int priority; 17 | final String prefix; 18 | 19 | @override 20 | String toString() => '$prefix($priority)'; 21 | } 22 | -------------------------------------------------------------------------------- /ffi/structs/structs_library/structs.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | struct Coordinate 6 | { 7 | double latitude; 8 | double longitude; 9 | }; 10 | 11 | struct Place 12 | { 13 | char *name; 14 | struct Coordinate coordinate; 15 | }; 16 | 17 | struct Coordinate create_coordinate(double latitude, double longitude); 18 | struct Place create_place(char *name, double latitude, double longitude); 19 | 20 | double distance(struct Coordinate, struct Coordinate); 21 | 22 | char *hello_world(); 23 | char *reverse(char *str, int length); 24 | -------------------------------------------------------------------------------- /extension_methods/example/generics.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// This file shows how you can specify extensions to generics with type 6 | /// bounds. For example, you can define an extension method for `List`, 7 | /// and it won't apply to `List`. 8 | void main() { 9 | print([1, 2, 3].sum); 10 | 11 | // Uncommenting the following line results in a static error. The `sum` 12 | // extension is not defined on lists of strings. 13 | // print(['a', 'b'].sum); 14 | } 15 | 16 | extension on List { 17 | int get sum => fold(0, (a, b) => a + b); 18 | } 19 | -------------------------------------------------------------------------------- /ffi/system_command/README.md: -------------------------------------------------------------------------------- 1 | FFI sample demonstrating invoking operating system commands: 2 | 3 | * `macos.dart`: Invoke the `system()` command in `libSystem.dylib` 4 | * `linux.dart`: Invoke the `system()` command in `libc.so.6` 5 | * `windows.dart`: Invoke the `ShellExecute` command in `shell32.dll` 6 | 7 | To run these samples: 8 | * Run `dart pub get` to get the dependencies 9 | * Run `dart macos.dart`, `dart linux.dart`, or `dart windows.dart` 10 | depending on the OS you are on. 11 | 12 | When run, you should see the system-default browser launch and load the 13 | Dart website, https://dart.dev 14 | 15 | ## Learn more 16 | 17 | To learn more about FFI, start with the [C interop using 18 | dart:ffi](https://dart.dev/guides/libraries/c-interop) guide on dart.dev. 19 | -------------------------------------------------------------------------------- /enhanced_enums/README.md: -------------------------------------------------------------------------------- 1 | # Enhanced enums samples 2 | 3 | This a set of samples that demonstrates the enhanced enums syntax 4 | and shows some common use cases of the feature. 5 | 6 | This feature is part of Dart 2.17. The programs in this folder won't 7 | compile in earlier versions. 8 | 9 | ## Instructions 10 | 11 | Read the source code in the `lib/` directory. The code is split into 12 | separate files according to topics or use cases. For instance, 13 | `lin/comparable_mixin.dart` demonstrates how a mixin can be used to add 14 | extra functionality to an enum. 15 | 16 | In `lib/complete_example.dart` you will find a complete example 17 | using all the functionality from enhanced enums. 18 | 19 | In `test/` you will find unit tests showing how the enums from the examples 20 | can be used. 21 | -------------------------------------------------------------------------------- /extension_methods/example/json_helpers.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// This file shows how you can define an extension to a JSON-like structure 6 | /// so that it can be used almost like a data class. 7 | /// 8 | /// This might create a false sense of (type) security, so use with caution. 9 | void main() { 10 | var json = {'id': 100, 'name': 'Dash'}; 11 | 12 | print("${json.name}'s ID is ${json.id}."); // Dash's ID is 100. 13 | } 14 | 15 | extension _MyJsonHelper on Map { 16 | int? get id => this['id'] as int?; 17 | 18 | String? get name => this['name'] as String?; 19 | } 20 | -------------------------------------------------------------------------------- /enhanced_enums/test/plain_test.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'package:enhanced_enums/plain.dart'; 6 | import 'package:test/test.dart'; 7 | 8 | void main() { 9 | test('Plain enum names', () { 10 | expect(Plain.foo.name, 'foo'); 11 | expect(Plain.bar.name, 'bar'); 12 | expect(Plain.baz.name, 'baz'); 13 | }); 14 | 15 | test('Plain enum index', () { 16 | expect(Plain.foo.index, 0); 17 | expect(Plain.bar.index, 1); 18 | expect(Plain.baz.index, 2); 19 | }); 20 | 21 | test('Get Plain enum values', () { 22 | expect(Plain.values, [Plain.foo, Plain.bar, Plain.baz]); 23 | }); 24 | } 25 | -------------------------------------------------------------------------------- /extension_methods/example/privacy_destination.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'package:extension_methods/privacy_source.dart'; 6 | 7 | /// This file shows how privacy works with extension methods. Extensions 8 | /// named without a leading `_` will be accessible from other files and 9 | /// libraries. Others won't. 10 | void main() { 11 | print('Flutter'.firstChar); 12 | 13 | // Uncommenting the following line results in a static error. The `addTwo` 14 | // extension is not reachable from here. 15 | // print(40.addTwo); 16 | 17 | // Same applies for unnamed extensions. 18 | // print(true.asInteger); 19 | } 20 | -------------------------------------------------------------------------------- /server/google_apis/Dockerfile: -------------------------------------------------------------------------------- 1 | # Official Dart image: https://hub.docker.com/_/dart 2 | # Specify the Dart SDK base image version using dart: (ex: dart:2.12) 3 | FROM dart:stable AS build 4 | 5 | # Resolve app dependencies. 6 | WORKDIR /app 7 | COPY pubspec.* ./ 8 | RUN dart pub get 9 | 10 | # Copy app source code and AOT compile it. 11 | COPY . . 12 | # Ensure packages are still up-to-date if anything has changed 13 | RUN dart pub get --offline 14 | RUN dart compile exe bin/server.dart -o bin/server 15 | 16 | # Build minimal serving image from AOT-compiled `/server` and required system 17 | # libraries and configuration files stored in `/runtime/` from the build stage. 18 | FROM scratch 19 | COPY --from=build /runtime/ / 20 | COPY --from=build /app/bin/server /app/bin/ 21 | 22 | # Start server. 23 | EXPOSE 8080 24 | CMD ["/app/bin/server"] 25 | -------------------------------------------------------------------------------- /server/google_apis/README.md: -------------------------------------------------------------------------------- 1 | A Dart HTTP service meant to be deployed to 2 | [Cloud Run](https://cloud.google.com/run) and which uses the 3 | [Cloud Firestore](https://firebase.google.com/products/firestore) features in 4 | [package:googleapis](https://pub.dev/packages/googleapis). 5 | 6 | - Increments a counter stored in Cloud Firestore via a transaction. 7 | - Based on [package:shelf](https://pub.dev/packages/shelf). 8 | - Includes a number of useful APIs in `lib/helpers.dart` which can be copied and 9 | used in other projects. 10 | - Follow instructions at 11 | https://cloud.google.com/run/docs/quickstarts/build-and-deploy to build and 12 | deploy on [Cloud Run](https://cloud.google.com/run). 13 | - To deploy this demo, you will also need to enable the 14 | [Cloud Firestore API](https://console.cloud.google.com/apis/api/firestore.googleapis.com). 15 | -------------------------------------------------------------------------------- /extension_methods/lib/privacy_source.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// This file defines three extensions. Only [UsableElsewhere] will be seen 6 | /// from other files. The other two extensions are local to this file. 7 | void main() { 8 | print(3.addTwo); 9 | print('Dash'.firstChar); 10 | print(true.asInteger); 11 | } 12 | 13 | extension UsableElsewhere on String { 14 | String get firstChar => substring(0, 1); 15 | } 16 | 17 | extension _UsableOnlyInThisFile on int { 18 | int get addTwo => this + 2; 19 | } 20 | 21 | /// This extension is unnamed, so it will also only be usable in this file. 22 | extension on bool { 23 | int get asInteger => this == true ? 1 : 0; 24 | } 25 | -------------------------------------------------------------------------------- /extension_methods/example/code_generation.dart: -------------------------------------------------------------------------------- 1 | class MyJsonAnnotation { 2 | const MyJsonAnnotation(); 3 | } 4 | 5 | @MyJsonAnnotation() 6 | class Planet { 7 | final String name; 8 | final int size; 9 | 10 | const Planet(this.name, this.size); 11 | } 12 | 13 | // --- generated (assume the following is in a separate file, and autogenerated) 14 | 15 | /// The following can now be generated by a package, making [Planet] 16 | /// serializable with almost no effort from you, the developer. 17 | /// 18 | /// Without extension methods, you would need to write things like: 19 | /// 20 | /// // No longer needed! 21 | /// Map toJson() => _$PlanetJsonifier(this); 22 | extension PlanetExtensions on Planet { 23 | static Planet from(Map json) => 24 | Planet(json['name'] as String, json['size'] as int); 25 | 26 | Map toJson() => {'name': name, 'size': size}; 27 | } 28 | -------------------------------------------------------------------------------- /extension_methods/README.md: -------------------------------------------------------------------------------- 1 | # Extension methods samples 2 | 3 | This a set of samples that demonstrates the extension methods syntax 4 | and shows some common use cases of the feature. 5 | 6 | This feature was added in Dart 2.6.0. The programs in this folder won't 7 | compile in earlier versions. 8 | 9 | ## Instructions 10 | 11 | Read the source code in the `example/` directory. The code is split into 12 | separate files according to topics or use cases. For instance, 13 | `example/generics.dart` explores the intersection between extension methods 14 | and generic types, while `example/operator_extensions.dart` shows how 15 | you can extend classes with operators. 16 | 17 | The files in `lib/` are support for the samples in `example/`. For instance, 18 | `lib/some_api.dart` is pretending to be an API from another package (because 19 | a common use case for extension methods is to modify classes whose source 20 | code we cannot edit). 21 | -------------------------------------------------------------------------------- /server/simple/README.md: -------------------------------------------------------------------------------- 1 | A simple Dart HTTP server using [package:shelf](https://pub.dev/packages/shelf). 2 | 3 | - Listens on "any IP" (0.0.0.0) instead of loop-back (localhost, 127.0.0.1) to 4 | allow remote connections. 5 | - Defaults to listening on port `8080`, but this can be configured by setting 6 | the `PORT` environment variable. (This is also the convention used by 7 | [Cloud Run](https://cloud.google.com/run).) 8 | - Includes `Dockerfile` for easy containerization 9 | 10 | To run this server locally, run as follows: 11 | 12 | ```bash 13 | $ dart run bin/server.dart 14 | ``` 15 | 16 | To deploy on [Cloud Run](https://cloud.google.com/run), click here 17 | 18 | [![Run on Google Cloud](https://deploy.cloud.run/button.svg)](https://deploy.cloud.run/?git_repo=https://github.com/dart-lang/samples.git&dir=server/simple) 19 | 20 | or follow 21 | [these instructions](https://cloud.google.com/run/docs/quickstarts/build-and-deploy/other). 22 | -------------------------------------------------------------------------------- /parameters/lib/named_parameters.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// This example shows the use of named arguments and parameters. 6 | /// 7 | /// See the test under `../test/named_parameters_test.dart` for its use. 8 | library; 9 | 10 | /// Function that counts the amount of [items] that match a given [predicate], 11 | /// with the option to skip the first [skip] elements. 12 | /// 13 | /// This function has three parameters: 14 | /// - Required positional parameter [predicate] 15 | /// - Required named parameter [items] 16 | /// - Optional named parameter [skip] 17 | int countWhere( 18 | bool Function(T) predicate, { 19 | required Iterable items, 20 | int skip = 0, 21 | }) { 22 | return items.skip(skip).where(predicate).length; 23 | } 24 | -------------------------------------------------------------------------------- /extension_methods/example/getter_extensions.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// This file shows how you can use extension methods for something akin 6 | /// to type literals. 7 | /// 8 | /// In this case, we can write `12.km` instead of `const MetricLength(12000)`. 9 | void main() { 10 | var a = 50.m; 11 | var b = 12.km; 12 | var c = a + b; 13 | print(c.meters); // 12050 14 | } 15 | 16 | class MetricLength { 17 | final int meters; 18 | 19 | const MetricLength(this.meters); 20 | 21 | MetricLength operator +(MetricLength other) => 22 | MetricLength(meters + other.meters); 23 | } 24 | 25 | extension MetricLengthGetters on int { 26 | MetricLength get m => MetricLength(this); 27 | MetricLength get km => MetricLength(this * 1000); 28 | } 29 | -------------------------------------------------------------------------------- /server/simple/Dockerfile: -------------------------------------------------------------------------------- 1 | # Official Dart image: https://hub.docker.com/_/dart 2 | # Specify the Dart SDK base image version using dart: (ex: dart:2.12) 3 | FROM dart:stable AS build 4 | 5 | # Resolve app dependencies. 6 | WORKDIR /app 7 | COPY pubspec.* ./ 8 | RUN dart pub get 9 | 10 | # Copy app source code and AOT compile it. 11 | COPY . . 12 | # Ensure packages are still up-to-date if anything has changed 13 | RUN dart pub get --offline 14 | RUN dart compile exe bin/server.dart -o bin/server 15 | 16 | # Build minimal serving image from AOT-compiled `/server` and required system 17 | # libraries and configuration files stored in `/runtime/` from the build stage. 18 | FROM scratch 19 | COPY --from=build /runtime/ / 20 | COPY --from=build /app/bin/server /app/bin/ 21 | 22 | # Include files in the /public directory to enable static asset handling 23 | COPY --from=build /app/public/ /public 24 | 25 | # Start server. 26 | EXPOSE 8080 27 | CMD ["/app/bin/server"] 28 | -------------------------------------------------------------------------------- /extension_methods/example/fluid_api.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'package:extension_methods/some_api.dart'; 6 | 7 | /// This file shows how extension methods allow you to move from helper 8 | /// functions to helper methods, for a more fluid API. 9 | void main() { 10 | var team = getTeam(); 11 | 12 | // Instead of something like removeYoungest(team) and then print(team), 13 | // we can do the following thanks to the extension below. 14 | team 15 | ..removeYoungest() 16 | ..show(); 17 | } 18 | 19 | extension on Group { 20 | void removeYoungest() { 21 | var sorted = people.toList() 22 | ..sort((a, b) => a.dayOfBirth.compareTo(b.dayOfBirth)); 23 | var youngest = sorted.last; 24 | people.remove(youngest); 25 | } 26 | 27 | void show() => print(this); 28 | } 29 | -------------------------------------------------------------------------------- /extension_methods/example/operator_extensions.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'package:extension_methods/some_api.dart'; 6 | 7 | /// This file shows that extension methods can be used in conjunction 8 | /// with operator overloading. 9 | void main() { 10 | var team = jean + betty; 11 | team += kay; 12 | print(team); 13 | 14 | var otherTeam = betty + marlyn; 15 | if (team > otherTeam) { 16 | print('The first team ($team) is larger than the other one ($otherTeam).'); 17 | } 18 | } 19 | 20 | extension GroupArithmetic on Group { 21 | Group operator +(Person person) => Group({...people, person}); 22 | bool operator >(Group other) => people.length > other.people.length; 23 | } 24 | 25 | extension PersonArithmetic on Person { 26 | Group operator +(Person other) => Group({this, other}); 27 | } 28 | -------------------------------------------------------------------------------- /isolates/README.md: -------------------------------------------------------------------------------- 1 | Additional samples for [Concurrency in Dart][concurrency-in-dart]. 2 | 3 | - `bin/send_and_receive.dart`: Demonstrates how to spawn a 4 | worker [`Isolate`][] with [`Isolate.run`][]. 5 | `Isolate.run` executes the specified function and returns the result 6 | to the main isolate efficiently using [`Isolate.exit`][] which avoids copying. 7 | - `bin/long_running_isolate.dart`: Similar to `send_and_receive.dart`, except 8 | that the spawned isolate is long running, responds to incoming messages from 9 | the main isolate, and sends responses until it receives a `null` over its 10 | [`SendPort`][]. 11 | 12 | [concurrency-in-dart]: https://dart.dev/guides/language/concurrency 13 | [`Isolate`]: https://api.dart.dev/stable/dart-isolate/Isolate-class.html 14 | [`Isolate.run`]: https://api.dart.dev/stable/dart-isolate/Isolate/run.html 15 | [`Isolate.exit`]: https://api.dart.dev/stable/dart-isolate/Isolate/exit.html 16 | [`SendPort`]: https://api.dart.dev/stable/dart-isolate/SendPort-class.html 17 | -------------------------------------------------------------------------------- /command_line/README.md: -------------------------------------------------------------------------------- 1 | # Command line app sample 2 | 3 | This sample demonstrates how to parse command line options into Dart objects 4 | using [`package:build_cli_annotations`][build-cli], read environment variables, 5 | use third-party packages like `package:github` and use core library APIs like 6 | DateTime. 7 | 8 | ## Adding new CLI options 9 | 10 | To add new command line options to `lib/src/options.dart`, update the `Options` 11 | class and re-run `build_runner`: 12 | 13 | ```bash 14 | dart run build_runner build 15 | ``` 16 | 17 | ## About this project 18 | 19 | `bin/github_activity.dart` is a command line application that fetches stats for 20 | a GitHub user and prints them to the console. 21 | 22 | Use the `--help` flag for usage instructions: 23 | 24 | ```bash 25 | ./github_activity --help 26 | ``` 27 | 28 | If you run into rate limiting issues, you can generate a GitHub token and set it 29 | to the `GITHUB_TOKEN` environment variable: 30 | 31 | ```bash 32 | export GITHUB_TOKEN= 33 | ``` 34 | 35 | [build-cli]: https://pub.dev/packages/build_cli_annotations 36 | -------------------------------------------------------------------------------- /.github/workflows/container_docker_test.yml: -------------------------------------------------------------------------------- 1 | name: container_docker_test 2 | on: 3 | push: 4 | branches: 5 | - main 6 | pull_request: 7 | schedule: 8 | - cron: "0 0 * * 0" 9 | 10 | defaults: 11 | run: 12 | shell: bash 13 | working-directory: server/simple 14 | 15 | env: 16 | PUB_ENVIRONMENT: bot.github 17 | 18 | jobs: 19 | test: 20 | runs-on: ubuntu-latest 21 | strategy: 22 | matrix: 23 | dart: [ stable ] 24 | steps: 25 | - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 26 | - name: Cache Pub hosted dependencies 27 | uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 28 | with: 29 | path: "~/.pub-cache/hosted" 30 | key: "os:ubuntu-latest;pub-cache-hosted;dart:stable" 31 | restore-keys: | 32 | os:ubuntu-latest;pub-cache-hosted 33 | os:ubuntu-latest 34 | - uses: dart-lang/setup-dart@e51d8e571e22473a2ddebf0ef8a2123f0ab2c02c 35 | with: 36 | sdk: ${{ matrix.dart }} 37 | - run: dart pub get 38 | - run: tool/docker_test_script.sh 39 | -------------------------------------------------------------------------------- /ffi/primitives/primitives_library/primitives.c: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | #include 6 | #include 7 | #include 8 | #include "primitives.h" 9 | 10 | int main() 11 | { 12 | printf("3 + 5 = %d\n", sum(3, 5)); 13 | int *mult = multiply(3, 5); 14 | printf("3 * 5 = %d\n", *mult); 15 | free(mult); 16 | int sub_num = 3; 17 | printf("3 - 5 = %d\n", subtract(&sub_num, 5)); 18 | return 0; 19 | } 20 | 21 | int sum(int a, int b) 22 | { 23 | return a + b; 24 | } 25 | 26 | int *multiply(int a, int b) 27 | { 28 | // Allocates native memory in C. 29 | int *mult = (int *)malloc(sizeof(int)); 30 | *mult = a * b; 31 | return mult; 32 | } 33 | 34 | void free_pointer(int *int_pointer) 35 | { 36 | // Free native memory in C which was allocated in C. 37 | free(int_pointer); 38 | } 39 | 40 | int subtract(int *a, int b) 41 | { 42 | return *a - b; 43 | } 44 | -------------------------------------------------------------------------------- /ffi/README.md: -------------------------------------------------------------------------------- 1 | # Dart FFI Samples 2 | 3 | A series of simple examples demonstrating how to call C libraries from Dart. 4 | 5 | This code is designed to work with *Dart version 2.12.0* and above. 6 | 7 | To learn more about FFI, start with the [C interop using 8 | dart:ffi](https://dart.dev/guides/libraries/c-interop) guide on dart.dev. 9 | 10 | ## Building native libraries 11 | 12 | Each sample uses [CMake][cmake] to generate a Makefile. To build the native 13 | library for each sample: 14 | 15 | ```bash 16 | cd hello_world/hello_library 17 | cmake . 18 | make 19 | ``` 20 | 21 | The `make` command creates a `libhello.dylib` (macOS), `libhello.dll` 22 | (Windows) or `libhello.so` (Linux) library file. 23 | 24 | ## Running 25 | 26 | Once the native library is built, run: 27 | 28 | ```bash 29 | dart pub get 30 | dart run .dart 31 | ``` 32 | 33 | ## macOS code signing 34 | 35 | The Dart binary can only load shared libraries that are *signed*. For more 36 | information, see [dart-lang/sdk/issues/38314][signing-issue] for details. 37 | 38 | [cmake]: https://cmake.org/ 39 | [signing-issue]: https://github.com/dart-lang/sdk/issues/38314 40 | -------------------------------------------------------------------------------- /isolates/bin/send_and_receive.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | // Read the file, spawn an isolate, send the file contents to the spawned 6 | // isolate, and wait for the parsed JSON. 7 | import 'dart:async'; 8 | import 'dart:convert'; 9 | import 'dart:io'; 10 | import 'dart:isolate'; 11 | 12 | const filename = 'json_01.json'; 13 | 14 | Future main() async { 15 | // Read and parse JSON data in a new isolate, 16 | // then store the returned Dart representation. 17 | final jsonData = await Isolate.run(() => _readAndParseJson(filename)); 18 | 19 | print('Received JSON with ${jsonData.length} keys'); 20 | } 21 | 22 | /// Reads the contents of the file with [filename], 23 | /// decodes the JSON, and returns the result. 24 | Future> _readAndParseJson(String filename) async { 25 | final fileData = await File(filename).readAsString(); 26 | final jsonData = jsonDecode(fileData) as Map; 27 | return jsonData; 28 | } 29 | -------------------------------------------------------------------------------- /extension_methods/example/core_type_extensions.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// This file shows how you can extend even basic types like [String] 6 | /// or [int]. Use with caution. 7 | void main() { 8 | var warning = 'Extensions are here!'; 9 | warning.scream(); // prints "EXTENSIONS ARE HERE!" 10 | 11 | // Extension methods ¯\_(ツ)_/¯ 12 | 5.times(() => print('hello')); 13 | 14 | print(null.stop('!!!')); // prints null!!! 15 | } 16 | 17 | extension Silly on String { 18 | void scream() => print(toUpperCase()); 19 | } 20 | 21 | extension Sillier on int { 22 | void times(void Function() f) { 23 | for (var i = 0; i < this; i++) { 24 | f(); 25 | } 26 | } 27 | } 28 | 29 | extension Silliest on Object { 30 | int nah() => hashCode + 42; 31 | Type please() => runtimeType; 32 | bool notAgain(Object other) => this != other; 33 | } 34 | 35 | extension ExtremelySilly on Object? { 36 | String stop(String x) => toString() + x; 37 | } 38 | -------------------------------------------------------------------------------- /ffi/hello_world/test/hello_world_test.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | import 'package:test/test.dart'; 4 | import 'package:test_utils/test_utils.dart'; 5 | 6 | void main() async { 7 | group('hello_world', () { 8 | test('make dylib + execute', () async { 9 | // run 'cmake .' 10 | var cmake = await Process.run('cmake', [ 11 | '.', 12 | ], workingDirectory: 'hello_library'); 13 | expect(cmake.exitCode, 0); 14 | 15 | // run 'make' 16 | var make = await Process.run( 17 | 'make', 18 | [], 19 | workingDirectory: 'hello_library', 20 | ); 21 | expect(make.exitCode, 0); 22 | 23 | var filePath = getLibraryFilePath('hello_library', 'hello'); 24 | var file = File(filePath); 25 | expect(await file.exists(), true, reason: '$filePath does not exist'); 26 | 27 | // Run the Dart script 28 | var dartProcess = await Process.run('dart', ['hello.dart']); 29 | 30 | // Verify program output 31 | expect(dartProcess.stderr, isEmpty); 32 | expect(dartProcess.stdout, equals('Hello World\n')); 33 | expect(dartProcess.exitCode, equals(0)); 34 | }); 35 | }); 36 | } 37 | -------------------------------------------------------------------------------- /extension_methods/lib/some_api.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// This is an API that we wrap with extension methods elsewhere. There is 6 | /// no extension method to be seen here. 7 | /// 8 | /// Imagine that this code is coming from a different package, so we can't 9 | /// directly change it. 10 | library; 11 | 12 | final betty = Person('Betty Holberton', DateTime(1917, 3, 7)); 13 | 14 | final jean = Person('Jean Bartik', DateTime(1924, 12, 27)); 15 | 16 | final kay = Person('Kay Antonelli', DateTime(1921, 2, 12)); 17 | 18 | final marlyn = Person('Marlyn Meltzer', DateTime(1922)); 19 | 20 | Group getTeam() => Group({jean, betty, kay, marlyn}); 21 | 22 | class Group { 23 | final Set people; 24 | 25 | const Group(this.people); 26 | 27 | @override 28 | String toString() => people.map((p) => p.name).join(', '); 29 | } 30 | 31 | class Person { 32 | final String name; 33 | final DateTime dayOfBirth; 34 | 35 | const Person(this.name, this.dayOfBirth); 36 | } 37 | -------------------------------------------------------------------------------- /package_constraint_solver/analysis_options.yaml: -------------------------------------------------------------------------------- 1 | # This file configures the static analysis results for your project (errors, 2 | # warnings, and lints). 3 | # 4 | # This enables the 'recommended' set of lints from `package:lints`. 5 | # This set helps identify many issues that may lead to problems when running 6 | # or consuming Dart code, and enforces writing Dart using a single, idiomatic 7 | # style and format. 8 | # 9 | # If you want a smaller set of lints you can change this to specify 10 | # 'package:lints/core.yaml'. These are just the most critical lints 11 | # (the recommended set includes the core lints). 12 | # The core lints are also what is used by pub.dev for scoring packages. 13 | 14 | include: package:lints/recommended.yaml 15 | 16 | # Uncomment the following section to specify additional rules. 17 | 18 | # linter: 19 | # rules: 20 | # - camel_case_types 21 | 22 | # analyzer: 23 | # exclude: 24 | # - path/to/excluded/files/** 25 | 26 | # For more information about the core and recommended set of lints, see 27 | # https://dart.dev/go/core-lints 28 | 29 | # For additional information about configuring this file, see 30 | # https://dart.dev/guides/language/analysis-options 31 | -------------------------------------------------------------------------------- /command_line/lib/src/util.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'package:github/github.dart'; 6 | 7 | import 'options.dart'; 8 | 9 | String? extractAction(Event event) => event.payload!['action']; 10 | 11 | String? extractUrl(Event event) => switch (event.type) { 12 | 'PullRequestEvent' => event.payload!['pull_request']['html_url'], 13 | 'IssuesEvent' => event.payload!['issue']['html_url'], 14 | _ => null, 15 | }; 16 | 17 | String? extractTitle(Event event) => switch (event.type) { 18 | 'PullRequestEvent' => event.payload!['pull_request']['title'], 19 | 'IssuesEvent' => event.payload!['issue']['title'], 20 | _ => null, 21 | }; 22 | 23 | int? extractIssueNumber(Event event) => switch (event.type) { 24 | 'PullRequestEvent' => event.payload!['pull_request']['number'], 25 | 'IssuesEvent' => event.payload!['issue']['number'], 26 | _ => null, 27 | }; 28 | 29 | bool isTooOld(DateTime? date, Interval interval) => 30 | date?.isBefore(DateTime.now().subtract(interval.duration)) ?? true; 31 | -------------------------------------------------------------------------------- /server/simple/test/server_test.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'package:test/test.dart'; 6 | import 'package:test_process/test_process.dart'; 7 | 8 | import 'test_definitions.dart'; 9 | 10 | void main() { 11 | late TestProcess proc; 12 | late int port; 13 | 14 | setUp(() async { 15 | proc = await TestProcess.start( 16 | 'dart', 17 | ['bin/server.dart'], 18 | environment: {'PORT': '0'}, 19 | ); 20 | 21 | final output = await proc.stdout.next; 22 | final match = _listeningPattern.firstMatch(output)!; 23 | port = int.parse(match[1]!); 24 | }); 25 | 26 | void testServer(String name, Future Function(String host) func) { 27 | test(name, () async { 28 | await func('http://localhost:$port'); 29 | await proc.kill(); 30 | }, timeout: _defaultTimeout); 31 | } 32 | 33 | runTests(testServer); 34 | } 35 | 36 | const _defaultTimeout = Timeout(Duration(seconds: 3)); 37 | 38 | final _listeningPattern = RegExp(r'Serving at http://[^:]+:(\d+)'); 39 | -------------------------------------------------------------------------------- /ffi/system_command/linux.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'dart:ffi' as ffi; 6 | 7 | import 'package:ffi/ffi.dart'; 8 | 9 | void main() { 10 | var result = system('xdg-open https://dart.dev'); 11 | print('Result: $result'); 12 | } 13 | 14 | /* 15 | #include 16 | int system(const char *string); 17 | 18 | https://man.openbsd.org/system.3 19 | */ 20 | 21 | // C header typedef: 22 | typedef SystemC = ffi.Int32 Function(ffi.Pointer command); 23 | 24 | // Dart header typedef 25 | typedef SystemDart = int Function(ffi.Pointer command); 26 | 27 | int system(String command) { 28 | // Load `stdlib`. On MacOS this is in libSystem.dylib. 29 | final dylib = ffi.DynamicLibrary.open('libc.so.6'); 30 | 31 | // Look up the `system` function. 32 | final systemP = dylib.lookupFunction('system'); 33 | 34 | // Allocate a pointer to a Utf8 array containing our command. 35 | final cmdP = command.toNativeUtf8(); 36 | 37 | // Invoke the command, and free the pointer. 38 | int result = systemP(cmdP); 39 | 40 | calloc.free(cmdP); 41 | 42 | return result; 43 | } 44 | -------------------------------------------------------------------------------- /ffi/system_command/macos.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'dart:ffi' as ffi; 6 | 7 | import 'package:ffi/ffi.dart'; 8 | 9 | void main() { 10 | var result = system('open https://dart.dev'); 11 | print('Result: $result'); 12 | } 13 | 14 | /* 15 | #include 16 | int system(const char *string); 17 | 18 | https://man.openbsd.org/system.3 19 | */ 20 | 21 | // C header typedef: 22 | typedef SystemC = ffi.Int32 Function(ffi.Pointer command); 23 | 24 | // Dart header typedef 25 | typedef SystemDart = int Function(ffi.Pointer command); 26 | 27 | int system(String command) { 28 | // Load `stdlib`. On MacOS this is in libSystem.dylib. 29 | final dylib = ffi.DynamicLibrary.open('/usr/lib/libSystem.dylib'); 30 | 31 | // Look up the `system` function. 32 | final systemP = dylib.lookupFunction('system'); 33 | 34 | // Allocate a pointer to a Utf8 array containing our command. 35 | final cmdP = command.toNativeUtf8(); 36 | 37 | // Invoke the command, and free the pointer. 38 | int result = systemP(cmdP); 39 | calloc.free(cmdP); 40 | 41 | return result; 42 | } 43 | -------------------------------------------------------------------------------- /enhanced_enums/test/complete_example_test.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'package:enhanced_enums/complete_example.dart'; 6 | import 'package:test/test.dart'; 7 | 8 | void main() { 9 | test('Calculate efficiency of Vehicles', () { 10 | expect(Vehicle.bicycle.carbonFootprint, 0); 11 | expect(Vehicle.bus.carbonFootprint, 16); 12 | expect(Vehicle.car.carbonFootprint, 80); 13 | }); 14 | 15 | test('Sort Vehicles by carbon footprint', () { 16 | final vehicles = Vehicle.values.toList(); 17 | 18 | // Sort using compareTo 19 | vehicles.sort(); 20 | 21 | // Expect order from more efficient to less efficient 22 | expect(vehicles, [Vehicle.bicycle, Vehicle.bus, Vehicle.car]); 23 | }); 24 | 25 | test('Calculate cost to replace tires', () { 26 | expect(Vehicle.bicycle.costToReplaceTires(pricePerTire: 10), 70); 27 | expect(Vehicle.car.costToReplaceTires(pricePerTire: 60), 290); 28 | expect(Vehicle.bus.costToReplaceTires(pricePerTire: 100), 650); 29 | }); 30 | 31 | test('Travel in a car', () { 32 | expect(Vehicle.car.travel(), 'I am traveling in a car!'); 33 | }); 34 | } 35 | -------------------------------------------------------------------------------- /ffi/test_utils/lib/test_utils.dart: -------------------------------------------------------------------------------- 1 | import 'dart:ffi'; 2 | import 'dart:io'; 3 | 4 | import 'package:path/path.dart' as path; 5 | 6 | DynamicLibrary getLibrary(String directory, String filename) => 7 | DynamicLibrary.open(getLibraryFilePath(directory, filename)); 8 | 9 | /// Gets the file path of a library, for the platform running this test 10 | /// 11 | /// Linux: {path to dart package}/hello_library/libfoo.so 12 | /// macOS: {path to dart package}/hello_library/libfoo.dylib 13 | /// Windows: {path to dart package}/hello_library/Debug/foo.dll 14 | String getLibraryFilePath(String directory, String filename) { 15 | var currentDirectory = Directory.current.path; 16 | 17 | // Windows doesn't use 18 | if (!Platform.isWindows) filename = 'lib$filename'; 19 | 20 | // Get the path to the library file 21 | var libraryPath = path.join(currentDirectory, directory, filename); 22 | if (Platform.isWindows) { 23 | libraryPath = path.join(currentDirectory, directory, 'Debug', filename); 24 | } 25 | 26 | // Add extension 27 | return path.setExtension(libraryPath, getPlatformExtension()); 28 | } 29 | 30 | String getPlatformExtension() { 31 | if (Platform.isLinux) return '.so'; 32 | if (Platform.isMacOS) return '.dylib'; 33 | if (Platform.isWindows) return '.dll'; 34 | throw 'Unsupported platform ${Platform.operatingSystem}'; 35 | } 36 | -------------------------------------------------------------------------------- /native_app/README.md: -------------------------------------------------------------------------------- 1 | # Native compilation sample 2 | 3 | This sample is a command line application that can be compiled to native code 4 | using the [`dart compile exe`][exe] command. 5 | 6 | ## Building and running an executable 7 | 8 | To create a standalone executable, run the `dart compile exe` command on 9 | a Dart file with a `main()` function. 10 | By default, it places the executable in the same directory. 11 | The `--output` or `-o` flag is used to change the location of the executable. 12 | 13 | ### Linux and macOS 14 | 15 | To build the executable: 16 | 17 | ```bash 18 | dart compile exe bin/main.dart -o hello_world 19 | ``` 20 | 21 | To run: 22 | 23 | ``` 24 | ./hello_world 25 | ``` 26 | 27 | ### Windows 28 | 29 | To build the executable: 30 | 31 | ```bash 32 | dart compile exe bin\main.dart -o hello_world.exe 33 | ``` 34 | 35 | To run: 36 | 37 | ``` 38 | hello_world.exe 39 | ``` 40 | 41 | ## Building an AOT snapshot 42 | 43 | The `--output-kind` or `-k` flag can be used to create an [AOT snapshot][]: 44 | 45 | ```bash 46 | dart compile aot-snapshot bin/main.dart -o hello_world.aot 47 | ``` 48 | 49 | This AOT snapshot can be run using the `dartaotruntime` command: 50 | 51 | ```bash 52 | dartaotruntime hello_world.aot 53 | ``` 54 | 55 | [exe]: https://dart.dev/tools/dart-compile#exe 56 | [AOT snapshot]: https://dart.dev/tools/dart-compile#aot-snapshot 57 | -------------------------------------------------------------------------------- /command_line/test/github_stats_test.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'package:github/github.dart'; 6 | import 'package:cli_app/src/formatter.dart'; 7 | import 'package:test/test.dart'; 8 | 9 | void main() { 10 | test('DefaultFormatter', () { 11 | var formatter = DefaultEventFormatter(); 12 | var actor = User()..login = 'substack'; 13 | var org = Organization(); 14 | var repo = Repository(); 15 | 16 | var event = Event( 17 | id: '', 18 | type: 'PullRequestEvent', 19 | createdAt: DateTime.utc(2019, 10, 1, 12), 20 | actor: actor, 21 | payload: { 22 | 'action': 'closed', 23 | 'pull_request': { 24 | 'html_url': 'https://github.com/peermaps/random-slicing/issues/2', 25 | }, 26 | }, 27 | org: org, 28 | repo: repo, 29 | ); 30 | 31 | var output = formatter.format(event); 32 | // Don't check exact date since it is formatted as local time. 33 | expect(output, contains('Tuesday, October 1 at ')); 34 | expect( 35 | output, 36 | contains( 37 | 'substack closed https://github.com/peermaps/random-slicing/issues/2', 38 | ), 39 | ); 40 | }); 41 | } 42 | -------------------------------------------------------------------------------- /ffi/primitives/test/primitives_test.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | import 'package:test/test.dart'; 4 | import 'package:test_utils/test_utils.dart'; 5 | 6 | void main() async { 7 | group('primitives', () { 8 | test('make dylib + execute', () async { 9 | // run 'cmake .' 10 | var cmake = await Process.run('cmake', [ 11 | '.', 12 | ], workingDirectory: 'primitives_library'); 13 | expect(cmake.exitCode, 0); 14 | 15 | // run 'make' 16 | var make = await Process.run( 17 | 'make', 18 | [], 19 | workingDirectory: 'primitives_library', 20 | ); 21 | expect(make.exitCode, 0); 22 | 23 | // Verify dynamic library was created 24 | var filePath = getLibraryFilePath('primitives_library', 'primitives'); 25 | var file = File(filePath); 26 | expect(await file.exists(), true, reason: '$filePath does not exist.'); 27 | 28 | // Run the Dart script 29 | var dartProcess = await Process.run('dart', ['primitives.dart']); 30 | expect(dartProcess.exitCode, equals(0), reason: dartProcess.stderr); 31 | 32 | // Verify program output 33 | expect(dartProcess.stderr, isEmpty); 34 | expect( 35 | dartProcess.stdout, 36 | equals( 37 | '3 + 5 = 8\n' 38 | '3 - 5 = -2\n' 39 | '3 * 5 = 15\n', 40 | ), 41 | ); 42 | }); 43 | }); 44 | } 45 | -------------------------------------------------------------------------------- /parameters/test/super_initializer_test.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'package:parameters/super_initalizer.dart'; 6 | import 'package:test/test.dart'; 7 | 8 | void main() { 9 | test('Create multiple instances of class Synth', () { 10 | // Constructor with optional argument, provided 11 | final juno = VintageSynth("Juno", polyphony: 6); 12 | expect(juno.toString(), "Synth Juno. Polyphony: 6, oscilators: 1"); 13 | 14 | // Constructor with optional argument, not provided 15 | final tb303 = VintageSynth("TB-303"); 16 | expect(tb303.toString(), "Synth TB-303. Polyphony: 1, oscilators: 1"); 17 | 18 | // Constructor with required argument 19 | final dx7 = DigitalSynth("DX7", polyphony: 6); 20 | expect(dx7.toString(), "Synth DX7. Polyphony: 6, oscilators: 1"); 21 | 22 | // Constructor with required positional arguments 23 | final ob6 = MultiOscillatorSynth("OB6", 5, 3); 24 | expect(ob6.toString(), "Synth OB6. Polyphony: 5, oscilators: 3"); 25 | 26 | // Constructor with a single required positional arguments 27 | final minimoog = FixedOscillatorSynth("MiniMoog"); 28 | expect(minimoog.toString(), "Synth MiniMoog. Polyphony: 1, oscilators: 3"); 29 | }); 30 | } 31 | -------------------------------------------------------------------------------- /null_safety/calculate_lix/text/lorem-ipsum.txt: -------------------------------------------------------------------------------- 1 | Lorem. ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor 2 | incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis 3 | nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 4 | Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu 5 | fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in 6 | culpa qui officia deserunt mollit anim id est laborum. 7 | 8 | Curabitur pretium tincidunt lacus. Nulla gravida orci a odio. Nullam varius, 9 | turpis et commodo pharetra, est eros bibendum elit, nec luctus magna felis 10 | sollicitudin mauris. Integer in mauris eu nibh euismod gravida. Duis ac tellus 11 | et risus vulputate vehicula. Donec lobortis risus a elit. Etiam tempor. Ut 12 | ullamcorper, ligula eu tempor congue, eros est euismod turpis, id tincidunt 13 | sapien risus a quam. Maecenas fermentum consequat mi. Donec fermentum. 14 | Pellentesque malesuada nulla a mi. Duis sapien sem, aliquet nec, commodo eget, 15 | consequat quis, neque. Aliquam faucibus, elit ut dictum aliquet, felis nisl 16 | adipiscing sapien, sed malesuada diam lacus eget erat. Cras mollis scelerisque 17 | nunc. Nullam arcu. Aliquam consequat. Curabitur augue lorem, dapibus quis, 18 | laoreet et, pretium ac, nisi. Aenean magna nisl, mollis quis, molestie eu, 19 | feugiat in, orci. In hac habitasse platea dictumst. 20 | -------------------------------------------------------------------------------- /ffi/hello_world/hello.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'dart:ffi' as ffi; 6 | import 'dart:io' show Platform, Directory; 7 | 8 | import 'package:path/path.dart' as path; 9 | 10 | // FFI signature of the hello_world C function 11 | typedef HelloWorldFunc = ffi.Void Function(); 12 | // Dart type definition for calling the C foreign function 13 | typedef HelloWorld = void Function(); 14 | 15 | void main() { 16 | // Open the dynamic library 17 | var libraryPath = path.join( 18 | Directory.current.path, 19 | 'hello_library', 20 | 'libhello.so', 21 | ); 22 | 23 | if (Platform.isMacOS) { 24 | libraryPath = path.join( 25 | Directory.current.path, 26 | 'hello_library', 27 | 'libhello.dylib', 28 | ); 29 | } 30 | 31 | if (Platform.isWindows) { 32 | libraryPath = path.join( 33 | Directory.current.path, 34 | 'hello_library', 35 | 'Debug', 36 | 'hello.dll', 37 | ); 38 | } 39 | 40 | final dylib = ffi.DynamicLibrary.open(libraryPath); 41 | 42 | // Look up the C function 'hello_world' 43 | final HelloWorld hello = dylib 44 | .lookup>('hello_world') 45 | .asFunction(); 46 | // Call the function 47 | hello(); 48 | } 49 | -------------------------------------------------------------------------------- /ffi/structs/test/structs_test.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | import 'package:test/test.dart'; 4 | import 'package:test_utils/test_utils.dart'; 5 | 6 | void main() async { 7 | group('structs', () { 8 | test('make dylib + execute', () async { 9 | // run 'cmake .' 10 | var cmake = await Process.run('cmake', [ 11 | '.', 12 | ], workingDirectory: 'structs_library'); 13 | expect(cmake.exitCode, 0); 14 | 15 | // run 'make' 16 | var make = await Process.run( 17 | 'make', 18 | [], 19 | workingDirectory: 'structs_library', 20 | ); 21 | expect(make.exitCode, 0); 22 | 23 | // Verify dynamic library was created 24 | var filePath = getLibraryFilePath('structs_library', 'structs'); 25 | var file = File(filePath); 26 | expect(await file.exists(), true, reason: '$filePath does not exist.'); 27 | 28 | // Run the Dart script 29 | var dartProcess = await Process.run('dart', ['structs.dart']); 30 | expect(dartProcess.exitCode, equals(0), reason: dartProcess.stderr); 31 | 32 | // Verify program output 33 | expect(dartProcess.stderr, isEmpty); 34 | expect(dartProcess.stdout, equals(_expected)); 35 | }); 36 | }); 37 | } 38 | 39 | const _expected = 40 | 'Hello World\n' 41 | 'backwards reversed is sdrawkcab\n' 42 | 'Coordinate is lat 3.5, long 4.6\n' 43 | 'The name of my place is My Home at 42.0, 24.0\n' 44 | 'distance between (2,2) and (5,6) = 5.0\n'; 45 | -------------------------------------------------------------------------------- /command_line/bin/github_activity.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'dart:io'; 6 | import 'package:cli_app/github_activity.dart'; 7 | import 'package:cli_app/src/formatter.dart'; 8 | 9 | void main(List args) { 10 | var options = parseOptions(args); 11 | 12 | if (options.help) { 13 | _printUsage(); 14 | return; 15 | } 16 | 17 | if (options.user?.isEmpty ?? true) { 18 | _printUsage(); 19 | return; 20 | } 21 | 22 | var fetcher = ActivityService( 23 | options.user!, 24 | options.verbose!, 25 | options.interval, 26 | formatter: _getFormatter(options), 27 | ); 28 | 29 | // Stream the github activity to the console 30 | fetcher.getActivityStrings().listen((s) { 31 | print(s); 32 | }) 33 | ..onDone(() => exit(0)) 34 | ..onError((e) => print('Unable to fetch stats:\n$e')); 35 | } 36 | 37 | /// Gets the correct [Formatter] defined by [Options] 38 | EventFormatter _getFormatter(Options options) { 39 | if (options.format == 'markdown') { 40 | return MarkdownEventFormatter(); 41 | } 42 | return DefaultEventFormatter(); 43 | } 44 | 45 | void _printUsage() { 46 | print(''' 47 | A command line utility for fetching a GitHub user's recent activity. 48 | 49 | Usage: github_activity [] 50 | 51 | Arguments: 52 | ${parser.usage} 53 | '''); 54 | } 55 | -------------------------------------------------------------------------------- /null_safety/calculate_lix/README.md: -------------------------------------------------------------------------------- 1 | # Null safety example: A CLI app for calculating lix 2 | 3 | This is a small code example of an app that calculates the 'lix' readability 4 | index for a text file. The implementation uses the Dart null safety feature, 5 | and is meant to demonstrate how this feature works in a practical example. 6 | 7 | ## Supported SDK versions 8 | 9 | The example requires Dart 2.12 or later. If you're using Flutter, you need 10 | Flutter 2.0 or later. 11 | 12 | ### Running from the terminal / command prompt 13 | 14 | To run the main app, type these commands in the terminal/command-prompt: 15 | 16 | ```cmd 17 | $ cd /null_safety/calculate_lix/ 18 | $ dart pub get 19 | $ dart run bin/main.dart text/lorem-ipsum.txt 20 | ``` 21 | 22 | ## Next steps 23 | 24 | Once you have the code running, here some suggestions for things to try: 25 | 26 | * In `lib/lix.dart` line 30, try to remove the `required` keyword from one or 27 | more fields in the constructor, and notice the error shown. 28 | 29 | * In `lib/lix.dart` line 49, try to delete the code that initializes one or more 30 | fields (e.g. `words: words`) and notice the error shown. 31 | 32 | * In `lib/lix.dart` line 9, try to make `words` a nullable variable (`int? 33 | words`), and notice how we don't get errors about not checking for null in 34 | the `_calculate()` method. 35 | 36 | * In `lib/lix.dart` line 22, try to remove the `late` keyword from 37 | `readability`, and notice how we get an error in the constructor. 38 | -------------------------------------------------------------------------------- /null_safety/calculate_lix/bin/main.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'dart:io'; 6 | 7 | import 'package:calculate_lix/lix.dart'; 8 | 9 | void main(List arguments) { 10 | // Parse the arguments; we expect a single argument containing the file name. 11 | if (arguments.length != 1) { 12 | printUsage(); 13 | exit(64); 14 | } else { 15 | // Get the file name. 16 | // 17 | // TIP: We're using null safe versions of the core libraries, and the type 18 | // of `arguments` is `List` which means that arguments cannot contain null 19 | // elements. As a result, the Dart analyzer knows that `fileName` isn't 20 | // null. 21 | final fileName = arguments[0]; 22 | print('Calculating Lix of "$fileName"'); 23 | 24 | // Calculate lix. 25 | try { 26 | final l = Lix.fromString(File(fileName).readAsStringSync()); 27 | print( 28 | 'Lix is: ${l.readability}, ${l.describe()} to read ' 29 | '(words: ${l.words}, long words: ${l.longWords}, ' 30 | 'periods: ${l.periods}).', 31 | ); 32 | } catch (error) { 33 | print( 34 | 'Invalid input, could not calculate lix!\n' 35 | 'The input text must contain at least one full sentence.', 36 | ); 37 | } 38 | } 39 | } 40 | 41 | void printUsage() { 42 | print('Usage: calculate_lix '); 43 | } 44 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2019, the Dart project authors. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following 11 | disclaimer in the documentation and/or other materials provided 12 | with the distribution. 13 | * Neither the name of Google LLC nor the names of its 14 | contributors may be used to endorse or promote products derived 15 | from this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /null_safety/calculate_lix/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2020, the Dart project authors. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following 11 | disclaimer in the documentation and/or other materials provided 12 | with the distribution. 13 | * Neither the name of Google LLC nor the names of its 14 | contributors may be used to endorse or promote products derived 15 | from this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /package_constraint_solver/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2023 the Dart project authors. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following 11 | disclaimer in the documentation and/or other materials provided 12 | with the distribution. 13 | * Neither the name of Google LLC nor the names of its 14 | contributors may be used to endorse or promote products derived 15 | from this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | 29 | -------------------------------------------------------------------------------- /server/simple/test/test_definitions.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'package:http/http.dart'; 6 | import 'package:test/test.dart'; 7 | 8 | void runTests( 9 | void Function(String name, Future Function(String host)) testServer, 10 | ) { 11 | testServer('root', (host) async { 12 | final response = await get(Uri.parse(host)); 13 | expect(response.statusCode, 200); 14 | expect(response.body, contains('pkg:shelf example')); 15 | expect(response.headers, contains('last-modified')); 16 | expect(response.headers, contains('date')); 17 | expect(response.headers, containsPair('content-type', 'text/html')); 18 | }); 19 | 20 | testServer('time', (host) async { 21 | final response = await get(Uri.parse('$host/time')); 22 | expect(response.statusCode, 200); 23 | final serverTime = DateTime.parse(response.body); 24 | final now = DateTime.now(); 25 | expect( 26 | serverTime.isAfter(now), 27 | isFalse, 28 | reason: 29 | 'Server time ($serverTime) should not be after current time ($now).', 30 | ); 31 | }); 32 | 33 | testServer('404', (host) async { 34 | var response = await get(Uri.parse('$host/not_here')); 35 | expect(response.statusCode, 404); 36 | expect(response.body, 'Route not found'); 37 | 38 | response = await post(Uri.parse(host)); 39 | // https://github.com/dart-lang/shelf_static/issues/53 - should 405 40 | expect(response.statusCode, 200); 41 | expect(response.body, contains('pkg:shelf example')); 42 | }); 43 | } 44 | -------------------------------------------------------------------------------- /package_constraint_solver/example/example.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2023, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'package:constraint_solver/constraint_solver.dart'; 6 | 7 | void main() { 8 | var doug = Guest('Doug', dislikes: ['artichoke']); 9 | var patrick = Guest('Patrick', dislikes: ['bananas']); 10 | var susan = Guest('Susan', dislikes: ['broccoli']); 11 | var variables = [doug, patrick, susan]; 12 | 13 | var meals = ['artichoke', 'bananas', 'broccoli']; 14 | 15 | var domains = {doug: meals, patrick: meals, susan: meals}; 16 | 17 | var csp = CSP(variables, domains); 18 | 19 | csp.addConstraint(AvoidDislikes(variables)); 20 | 21 | var result = csp.backtrackingSearch(); 22 | print(result); 23 | } 24 | 25 | class Guest { 26 | final String name; 27 | final List dislikes; 28 | 29 | Guest(this.name, {this.dislikes = const []}); 30 | 31 | @override 32 | String toString() { 33 | return name; 34 | } 35 | } 36 | 37 | class AvoidDislikes extends Constraint { 38 | AvoidDislikes(super.variables); 39 | 40 | @override 41 | bool isSatisfied(Map assignment) { 42 | Set assignedItems = {}; 43 | for (var entry in assignment.entries) { 44 | var person = entry.key; 45 | var item = entry.value; 46 | 47 | if (person.dislikes.contains(item)) { 48 | return false; 49 | } 50 | assignedItems.add(item); 51 | } 52 | 53 | // Check that no duplicate items were assigned. 54 | if (assignedItems.length != assignment.length) { 55 | return false; 56 | } 57 | return true; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /command_line/lib/src/options.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'package:build_cli_annotations/build_cli_annotations.dart'; 6 | 7 | part 'options.g.dart'; 8 | 9 | /// The command line argument parser generated by the `build_cli_annotations` 10 | /// package. 11 | ArgParser get parser => _$populateOptionsParser(ArgParser(usageLineLength: 80)); 12 | 13 | /// The command line options for this app 14 | @CliOptions() 15 | class Options { 16 | @CliOption(abbr: 'u', help: 'Required. The GitHub user') 17 | final String? user; 18 | 19 | @CliOption( 20 | abbr: 'i', 21 | help: 'The time interval to filter events.', 22 | allowed: ['day', 'week', 'month'], 23 | defaultsTo: Interval.week, 24 | ) 25 | Interval interval; 26 | 27 | @CliOption(abbr: 'v', defaultsTo: false, help: 'Print additional event types') 28 | final bool? verbose; 29 | 30 | @CliOption( 31 | abbr: 'f', 32 | help: 33 | 'The format to display. Defaults to ' 34 | '"Friday, October 18 at 13:55 PM: opened "', 35 | allowed: ['default', 'markdown'], 36 | ) 37 | final String? format; 38 | 39 | @CliOption(abbr: 'h', negatable: false, help: 'Prints usage information.') 40 | final bool help; 41 | 42 | Options(this.user, this.interval, this.verbose, this.format, this.help); 43 | } 44 | 45 | /// The time interval used to filter events. 46 | enum Interval { 47 | day, 48 | week, 49 | month; 50 | 51 | Duration get duration => switch (this) { 52 | Interval.day => const Duration(days: 1), 53 | Interval.week => const Duration(days: 7), 54 | Interval.month => const Duration(days: 30), 55 | }; 56 | } 57 | -------------------------------------------------------------------------------- /parameters/test/named_parameters_test.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'package:parameters/named_parameters.dart'; 6 | import 'package:test/test.dart'; 7 | 8 | /// This example shows the use of named arguments. 9 | /// 10 | /// Starting in Dart 2.17, named arguments can be used at any position in the 11 | /// arguments list, instead of only after the positional arguments. 12 | /// 13 | /// In the following tests, the method [countWhere] is called 14 | /// with a different argument list order to show this. 15 | void main() { 16 | test('named argument after positional argument', () { 17 | final list = [0, 2, 42, 91]; 18 | 19 | // `items` named argument appears after the positional argument `predicate` 20 | // Default argument `skip` is not provided 21 | final total = countWhere((item) { 22 | return item % 2 == 0; 23 | }, items: list); 24 | 25 | expect(total, 3); 26 | }); 27 | 28 | test('named argument before positional argument', () { 29 | final list = [0, 2, 42, 91]; 30 | 31 | // `items` named argument appears before the positional argument `predicate` 32 | // Default argument `skip` is not provided 33 | final total = countWhere(items: list, (item) { 34 | return item % 2 == 0; 35 | }); 36 | 37 | expect(total, 3); 38 | }); 39 | 40 | test('positional argument between named arguments', () { 41 | final list = [0, 2, 42, 91]; 42 | 43 | // positional argument `predicate` appears between 44 | // named arguments `items` and `skip` 45 | final total = countWhere(items: list, (item) { 46 | return item % 2 == 0; 47 | }, skip: 1); 48 | 49 | expect(total, 2); 50 | }); 51 | } 52 | -------------------------------------------------------------------------------- /command_line/lib/src/formatter.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'package:github/github.dart'; 6 | import 'package:intl/intl.dart'; 7 | import 'util.dart' as util; 8 | 9 | /// Formats an [Event] for console output. 10 | abstract class EventFormatter { 11 | String format(Event event); 12 | } 13 | 14 | /// Returns a formatted string of the form: 15 | /// `Friday, October 18 at 13:55 PM: opened `. 16 | class DefaultEventFormatter implements EventFormatter { 17 | static final DateFormat dateFormat = DateFormat("EEEE, MMMM d 'at' HH:mm a"); 18 | 19 | const DefaultEventFormatter(); 20 | 21 | @override 22 | String format(Event event) { 23 | var date = dateFormat.format(event.createdAt!.toLocal()); 24 | var type = event.type; 25 | var username = event.actor!.login; 26 | var url = util.extractUrl(event); 27 | if (url == null) { 28 | return '$date: [$type]'; 29 | } 30 | var action = util.extractAction(event); 31 | 32 | return '$date: $username $action $url'; 33 | } 34 | } 35 | 36 | class MarkdownEventFormatter implements EventFormatter { 37 | static final DateFormat dateFormat = DateFormat('EEE, M/d/y'); 38 | 39 | @override 40 | String format(Event event) { 41 | var date = dateFormat.format(event.createdAt!.toLocal()); 42 | var type = event.type; 43 | var action = util.extractAction(event); 44 | var url = util.extractUrl(event); 45 | if (url == null) { 46 | return '- ($date): [$type]'; 47 | } 48 | var title = util.extractTitle(event); 49 | var repoName = event.repo!.name; 50 | var issueNumber = util.extractIssueNumber(event); 51 | 52 | return '- ($date): $action "$title" ([$repoName/$issueNumber]($url))'; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /server/google_apis/bin/server.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'dart:convert'; 6 | 7 | import 'package:google_cloud/google_cloud.dart'; 8 | import 'package:googleapis/firestore/v1.dart'; 9 | import 'package:googleapis_auth/auth_io.dart'; 10 | import 'package:shelf/shelf.dart'; 11 | import 'package:shelf_router/shelf_router.dart'; 12 | 13 | Future main() async { 14 | final projectId = await computeProjectId(); 15 | print('Current GCP project id: $projectId'); 16 | 17 | final authClient = await clientViaApplicationDefaultCredentials( 18 | scopes: [FirestoreApi.datastoreScope], 19 | ); 20 | 21 | try { 22 | final api = FirestoreApi(authClient); 23 | 24 | Future incrementHandler(Request request) async { 25 | final result = await api.projects.databases.documents.commit( 26 | _incrementRequest(projectId), 27 | 'projects/$projectId/databases/(default)', 28 | ); 29 | 30 | return Response.ok( 31 | JsonUtf8Encoder(' ').convert(result), 32 | headers: {'content-type': 'application/json'}, 33 | ); 34 | } 35 | 36 | final router = Router()..get('/', incrementHandler); 37 | 38 | await serveHandler(router.call); 39 | } finally { 40 | authClient.close(); 41 | } 42 | } 43 | 44 | CommitRequest _incrementRequest(String projectId) => CommitRequest( 45 | writes: [ 46 | Write( 47 | transform: DocumentTransform( 48 | document: 49 | 'projects/$projectId/databases/(default)/documents/settings/count', 50 | fieldTransforms: [ 51 | FieldTransform( 52 | fieldPath: 'count', 53 | increment: Value(integerValue: '1'), 54 | ), 55 | ], 56 | ), 57 | ), 58 | ], 59 | ); 60 | -------------------------------------------------------------------------------- /server/simple/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | pkg:shelf example 10 | 11 | 12 | 36 | 37 | 38 |

pkg:shelf example

39 | Dashland 40 |

This file is being served by package:shelf_static from the 42 | /public directory.

43 | 44 |

This app uses package:shelf_router to define several 46 | code-based handlers:

47 | 53 | 54 |

55 | The last handler is defined with regular expressions to handle requests to /sum/1/2 56 | and /sum/35/7, 57 | but not /sum/bob/john or /sum/1/2/3. 58 |

59 | 60 | 61 | 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /ffi/system_command/windows.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'dart:ffi' as ffi; 6 | 7 | import 'package:ffi/ffi.dart'; 8 | 9 | void main() { 10 | shellExecute('open', 'https://dart.dev'); 11 | } 12 | 13 | /* 14 | HINSTANCE ShellExecuteW( 15 | HWND hwnd, 16 | LPCWSTR lpOperation, 17 | LPCWSTR lpFile, 18 | LPCWSTR lpParameters, 19 | LPCWSTR lpDirectory, 20 | INT nShowCmd 21 | ); 22 | 23 | https://docs.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shellexecutew 24 | */ 25 | typedef ShellExecuteC = 26 | ffi.Int32 Function( 27 | ffi.Pointer hwnd, 28 | ffi.Pointer lpOperation, 29 | ffi.Pointer lpFile, 30 | ffi.Pointer lpParameters, 31 | ffi.Pointer lpDirectory, 32 | ffi.Uint32 nShowCmd, 33 | ); 34 | typedef ShellExecuteDart = 35 | int Function( 36 | ffi.Pointer parentWindow, 37 | ffi.Pointer operation, 38 | ffi.Pointer file, 39 | ffi.Pointer parameters, 40 | ffi.Pointer directory, 41 | int showCmd, 42 | ); 43 | 44 | int shellExecute(String operation, String file) { 45 | // Load shell32. 46 | final dylib = ffi.DynamicLibrary.open('shell32.dll'); 47 | 48 | // Look up the `ShellExecuteW` function. 49 | final shellExecuteP = dylib.lookupFunction( 50 | 'ShellExecuteW', 51 | ); 52 | 53 | // Allocate pointers to Utf8 arrays containing the command arguments. 54 | final operationP = operation.toNativeUtf16(); 55 | final fileP = file.toNativeUtf16(); 56 | const int SW_SHOWNORMAL = 1; 57 | 58 | // Invoke the command, and free the pointers. 59 | var result = shellExecuteP( 60 | ffi.nullptr, 61 | operationP, 62 | fileP, 63 | ffi.nullptr, 64 | ffi.nullptr, 65 | SW_SHOWNORMAL, 66 | ); 67 | calloc.free(operationP); 68 | calloc.free(fileP); 69 | 70 | return result; 71 | } 72 | -------------------------------------------------------------------------------- /command_line/lib/src/options.g.dart: -------------------------------------------------------------------------------- 1 | // GENERATED CODE - DO NOT MODIFY BY HAND 2 | 3 | part of 'options.dart'; 4 | 5 | // ************************************************************************** 6 | // CliGenerator 7 | // ************************************************************************** 8 | 9 | T _$enumValueHelper(Map enumValues, String source) => enumValues 10 | .entries 11 | .singleWhere( 12 | (e) => e.value == source, 13 | orElse: () => throw ArgumentError( 14 | '`$source` is not one of the supported values: ' 15 | '${enumValues.values.join(', ')}', 16 | ), 17 | ) 18 | .key; 19 | 20 | Options _$parseOptionsResult(ArgResults result) => Options( 21 | result['user'] as String?, 22 | _$enumValueHelper(_$IntervalEnumMapBuildCli, result['interval'] as String), 23 | result['verbose'] as bool?, 24 | result['format'] as String?, 25 | result['help'] as bool, 26 | ); 27 | 28 | const _$IntervalEnumMapBuildCli = { 29 | Interval.day: 'day', 30 | Interval.week: 'week', 31 | Interval.month: 'month', 32 | }; 33 | 34 | ArgParser _$populateOptionsParser(ArgParser parser) => parser 35 | ..addOption('user', abbr: 'u', help: 'Required. The GitHub user') 36 | ..addOption( 37 | 'interval', 38 | abbr: 'i', 39 | help: 'The time interval to filter events.', 40 | defaultsTo: 'week', 41 | allowed: ['day', 'week', 'month'], 42 | ) 43 | ..addFlag( 44 | 'verbose', 45 | abbr: 'v', 46 | help: 'Print additional event types', 47 | defaultsTo: false, 48 | ) 49 | ..addOption( 50 | 'format', 51 | abbr: 'f', 52 | help: 53 | 'The format to display. Defaults to "Friday, October 18 at 13:55 PM: opened "', 54 | allowed: ['default', 'markdown'], 55 | ) 56 | ..addFlag( 57 | 'help', 58 | abbr: 'h', 59 | help: 'Prints usage information.', 60 | negatable: false, 61 | ); 62 | 63 | final _$parserForOptions = _$populateOptionsParser(ArgParser()); 64 | 65 | Options parseOptions(List args) { 66 | final result = _$parserForOptions.parse(args); 67 | return _$parseOptionsResult(result); 68 | } 69 | -------------------------------------------------------------------------------- /ffi/structs/structs_library/structs.c: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | #include 6 | #include 7 | #include 8 | #include "structs.h" 9 | 10 | int main() 11 | { 12 | printf("%s\n", hello_world()); 13 | char* backwards = "backwards"; 14 | printf("%s reversed is %s\n", backwards, reverse(backwards, 9)); 15 | 16 | struct Coordinate coord = create_coordinate(3.5, 4.6); 17 | printf("Coordinate is lat %.2f, long %.2f\n", coord.latitude, coord.longitude); 18 | 19 | struct Place place = create_place("My Home", 42.0, 24.0); 20 | printf("The name of my place is %s at %.2f, %.2f\n", place.name, place.coordinate.latitude, place.coordinate.longitude); 21 | 22 | return 0; 23 | } 24 | 25 | char *hello_world() 26 | { 27 | return "Hello World"; 28 | } 29 | 30 | char *reverse(char *str, int length) 31 | { 32 | // Allocates native memory in C. 33 | char *reversed_str = (char *)malloc((length + 1) * sizeof(char)); 34 | for (int i = 0; i < length; i++) 35 | { 36 | reversed_str[length - i - 1] = str[i]; 37 | } 38 | reversed_str[length] = '\0'; 39 | return reversed_str; 40 | } 41 | 42 | void free_string(char *str) 43 | { 44 | // Free native memory in C which was allocated in C. 45 | free(str); 46 | } 47 | 48 | struct Coordinate create_coordinate(double latitude, double longitude) 49 | { 50 | struct Coordinate coordinate; 51 | coordinate.latitude = latitude; 52 | coordinate.longitude = longitude; 53 | return coordinate; 54 | } 55 | 56 | struct Place create_place(char *name, double latitude, double longitude) 57 | { 58 | struct Place place; 59 | place.name = name; 60 | place.coordinate = create_coordinate(latitude, longitude); 61 | return place; 62 | } 63 | 64 | double distance(struct Coordinate c1, struct Coordinate c2) { 65 | double xd = c2.latitude - c1.latitude; 66 | double yd = c2.longitude - c1.longitude; 67 | return sqrt(xd*xd + yd*yd); 68 | } 69 | 70 | -------------------------------------------------------------------------------- /package_constraint_solver/test/constraint_solver_test.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2023, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'package:checks/checks.dart'; 6 | import 'package:constraint_solver/constraint_solver.dart'; 7 | import 'package:test/test.dart'; 8 | 9 | class Guest { 10 | final String name; 11 | final List dislikes; 12 | 13 | Guest(this.name, {this.dislikes = const []}); 14 | 15 | @override 16 | String toString() { 17 | return name; 18 | } 19 | } 20 | 21 | class AvoidDislikes extends Constraint { 22 | AvoidDislikes(super.variables); 23 | 24 | @override 25 | bool isSatisfied(Map assignment) { 26 | Set assignedItems = {}; 27 | for (var entry in assignment.entries) { 28 | var person = entry.key; 29 | var item = entry.value; 30 | 31 | if (person.dislikes.contains(item)) { 32 | return false; 33 | } 34 | assignedItems.add(item); 35 | } 36 | 37 | // Check that no duplicate items were assigned. 38 | if (assignedItems.length != assignment.length) { 39 | return false; 40 | } 41 | return true; 42 | } 43 | } 44 | 45 | void main() { 46 | group('constraint satisfaction framework', () { 47 | test('Satisfies constraints', () { 48 | var doug = Guest('Doug', dislikes: ['artichoke']); 49 | var patrick = Guest('Patrick', dislikes: ['bananas']); 50 | var susan = Guest('Susan', dislikes: ['broccoli']); 51 | 52 | var variables = [doug, patrick, susan]; 53 | 54 | var meals = ['artichoke', 'bananas', 'broccoli']; 55 | 56 | var domains = {doug: meals, patrick: meals, susan: meals}; 57 | 58 | var csp = CSP(variables, domains); 59 | csp.addConstraint(AvoidDislikes(variables)); 60 | 61 | var result = csp.backtrackingSearch(); 62 | 63 | check(result).isNotNull().length.equals(3); 64 | 65 | check(result).isNotNull().deepEquals({ 66 | doug: 'bananas', 67 | patrick: 'broccoli', 68 | susan: 'artichoke', 69 | }); 70 | }); 71 | }); 72 | } 73 | -------------------------------------------------------------------------------- /package_constraint_solver/README.md: -------------------------------------------------------------------------------- 1 | A general-purpose backtracking constraint satisfaction algorithm. 2 | 3 | [![Coverage Status](https://coveralls.io/repos/github/dart-lang/samples/badge.svg?branch=main)](https://coveralls.io/github/dart-lang/samples?branch=main) 4 | [![pub package](https://img.shields.io/pub/v/constraint_solver.svg)](https://pub.dev/packages/constraint_solver) 5 | 6 | ## Usage 7 | 8 | A constraint satisfaction problem (CSP) can be used to model problems where 9 | a solution must be found to satisfy one or more constraints. 10 | Examples of such a problem include event scheduling, or map coloring. 11 | 12 | A CSP framework is a set of _variables_ that can be assigned within a range 13 | called a _domain_. For example, If we are cooking dinner for three guests, we 14 | would define them as variables that can be assigned a meal: 15 | 16 | ```dart 17 | var doug = Person('Doug', dislikes: ['artichoke']); 18 | var patrick = Person('Patrick', dislikes: ['bananas']); 19 | var susan = Person('Susan', dislikes: ['broccoli']); 20 | 21 | var variables = [doug, patrick, susan]; 22 | ``` 23 | 24 | And the domains (the meal for each guest) could be modeled as a list strings, 25 | one of which will be assigned to each variable (guest). 26 | 27 | ```dart 28 | var meals = ['artichoke', 'bananas', 'broccoli']; 29 | 30 | var domains = { 31 | doug: meals, 32 | patrick: meals, 33 | susan: meals, 34 | }; 35 | ``` 36 | 37 | Finally, a constraint can be defined by subclassing of the `Constraint` class: 38 | 39 | ```dart 40 | class AvoidDislikes extends Constraint { 41 | AvoidDislikes(super.variables); 42 | 43 | @override 44 | bool isSatisfied(Map assignment) { 45 | // ... 46 | } 47 | } 48 | ``` 49 | 50 | To run a backtracking search of the solution space, instantiate the `CSP` class 51 | and call the `backtrackingSearch` function: 52 | 53 | ```dart 54 | var csp = CSP(variables, domains); 55 | 56 | csp.addConstraint(AvoidDislikes(variables)); 57 | 58 | var result = csp.backtrackingSearch(); 59 | print(result); 60 | ``` 61 | 62 | For complete examples, see the 63 | [examples/](https://github.com/dart-lang/samples/tree/main/package_constraint_solver/example) 64 | directory. 65 | 66 | ## References 67 | 68 | _Classic Computer Science Problems in Java_ - David Kopec 69 | -------------------------------------------------------------------------------- /ffi/system_command/win32ui.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'dart:ffi'; 6 | 7 | import 'package:ffi/ffi.dart'; 8 | 9 | void main() { 10 | messageBox('こんにちは窓', 'Hello Windows'); 11 | } 12 | 13 | /* MessageBoxW is the UTF16 (wchar_t) version of MessageBox. 14 | int MessageBoxW( 15 | HWND hWnd, 16 | LPCWSTR lpText, 17 | LPCWSTR lpCaption, 18 | UINT uType 19 | ); 20 | */ 21 | typedef MessageBoxC = 22 | Int32 Function( 23 | Pointer hwnd, 24 | Pointer lpText, 25 | Pointer lpCaption, 26 | Uint32 uType, 27 | ); 28 | typedef MessageBoxDart = 29 | int Function( 30 | Pointer parentWindow, 31 | Pointer message, 32 | Pointer caption, 33 | int type, 34 | ); 35 | 36 | const MB_ABORTRETRYIGNORE = 0x00000002; 37 | const MB_CANCELTRYCONTINUE = 0x00000006; 38 | const MB_HELP = 0x00004000; 39 | const MB_OK = 0x00000000; 40 | const MB_OKCANCEL = 0x00000001; 41 | const MB_RETRYCANCEL = 0x00000005; 42 | const MB_YESNO = 0x00000004; 43 | const MB_YESNOCANCEL = 0x00000003; 44 | 45 | const MB_ICONEXCLAMATION = 0x00000030; 46 | const MB_ICONWARNING = 0x00000030; 47 | const MB_ICONINFORMATION = 0x00000040; 48 | const MB_ICONASTERISK = 0x00000040; 49 | const MB_ICONQUESTION = 0x00000020; 50 | const MB_ICONSTOP = 0x00000010; 51 | const MB_ICONERROR = 0x00000010; 52 | const MB_ICONHAND = 0x00000010; 53 | 54 | int messageBox(String message, String caption) { 55 | // Load user32. 56 | final user32 = DynamicLibrary.open('user32.dll'); 57 | 58 | // Look up the `MessageBoxW` function. 59 | final messageBoxP = user32.lookupFunction( 60 | 'MessageBoxW', 61 | ); 62 | 63 | // Allocate pointers to Utf16 arrays containing the command arguments. 64 | final messageP = message.toNativeUtf16(); 65 | final captionP = caption.toNativeUtf16(); 66 | 67 | // Invoke the command, and free the pointers. 68 | final result = messageBoxP( 69 | nullptr, 70 | messageP, 71 | captionP, 72 | MB_OK | MB_ICONINFORMATION, 73 | ); 74 | calloc.free(messageP); 75 | calloc.free(captionP); 76 | 77 | return result; 78 | } 79 | -------------------------------------------------------------------------------- /enhanced_enums/lib/complete_example.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Complete example that showcases the different use cases for dart enums 6 | /// in a real scenario. 7 | /// 8 | /// Enum that represents different types of vehicles. 9 | enum Vehicle with FlatTireMixin, Traveler implements Comparable { 10 | car(tires: 4, passengers: 5, carbonPerKilometer: 400), 11 | bus(tires: 6, passengers: 50, carbonPerKilometer: 800), 12 | bicycle(tires: 2, passengers: 1, carbonPerKilometer: 0); 13 | 14 | const Vehicle({ 15 | required this.tires, 16 | required this.passengers, 17 | required this.carbonPerKilometer, 18 | }); 19 | 20 | /// Number of tires of this Vehicle, part of [FlatTireMixin]. 21 | @override 22 | final int tires; 23 | 24 | /// Number of passengers the Vehicle can transport. 25 | final int passengers; 26 | 27 | /// Carbon in grams per kilometer. 28 | final int carbonPerKilometer; 29 | 30 | /// Method that calculates the Carbon Footprint of a Vehicle per passenger. 31 | int get carbonFootprint => (carbonPerKilometer / passengers).round(); 32 | 33 | /// Comparable uses [carbonFootprint] to compare Vehicles. 34 | @override 35 | int compareTo(Vehicle other) => carbonFootprint - other.carbonFootprint; 36 | } 37 | 38 | /// Mixin that adds extra functionality. 39 | /// 40 | /// This Mixin introduces the [tires] member and a method [costToReplaceTires] 41 | /// to calculate the cost of replacing the tires. 42 | mixin FlatTireMixin { 43 | /// Fixed fee to add to the total cost. 44 | static const fee = 50; 45 | 46 | /// Number of tires getter, to be implemented by Enum. 47 | int get tires; 48 | 49 | /// Calculates the price to replace all tires. 50 | int costToReplaceTires({required int pricePerTire}) { 51 | return tires * pricePerTire + fee; 52 | } 53 | } 54 | 55 | /// Mixin that adds Enum specific functionality 56 | /// 57 | /// This mixin adds the [travel] method, that returns a String 58 | /// with the Enum name in it. 59 | /// 60 | /// This mixin can access the property [name] from the Enum. 61 | mixin Traveler on Enum { 62 | String travel() { 63 | return 'I am traveling in a $name!'; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Dart samples 2 | 3 | [![CI](https://github.com/dart-lang/samples/workflows/Dart%20CI/badge.svg)](https://github.com/dart-lang/samples/actions?query=branch%3Amain) 4 | 5 | A collection of [Dart][dart] programs that illustrate features and best 6 | practices. For a list of community-maintained projects, see [Awesome 7 | Dart][awesome-dart]. 8 | 9 | ## Index 10 | 11 | - [command_line](https://github.com/dart-lang/samples/tree/main/command_line) - 12 | A command line app that parses command-line options and fetches from GitHub. 13 | - [extension_methods](https://github.com/dart-lang/samples/tree/main/extension_methods) - 14 | A set of samples that demonstrates the extension methods syntax and shows some 15 | common use cases of the feature. 16 | - [null_safety/calculate_lix](https://github.com/dart-lang/samples/tree/main/null_safety/calculate_lix) - 17 | A sample app that calculates the 'lix' readability index with an 18 | implementation that uses the tech preview of Dart's new null safety feature. 19 | - [ffi](https://github.com/dart-lang/samples/tree/main/ffi) - A series of 20 | simple examples demonstrating how to call C libraries from Dart. 21 | - [isolates](https://github.com/dart-lang/samples/tree/main/isolates) - Command line 22 | applications that demonstrate how to work with Concurrency in Dart using isolates. 23 | The examples read and parse JSON content in a worker isolate, and return the result to 24 | the main isolate. 25 | - [native_app](https://github.com/dart-lang/samples/tree/main/native_app) - A 26 | command line application that can be compiled to native code using 27 | `dart compile exe`. 28 | - [server](https://github.com/dart-lang/samples/tree/main/server) - Examples 29 | of running Dart on the server. 30 | - [package_constraint_solver](https://github.com/dart-lang/samples/tree/main/package_constraint_solver) - Demonstrates best-practices for publishing packages on pub.dev. 31 | 32 | ## More samples 33 | 34 | - [Pop, Pop, Win!][pop-pop-win] **(Dart team)** - An implementation of 35 | Minesweeper in Dart. 36 | 37 | ## Contributing 38 | 39 | See the [Contributing guide][contributing] for details on how to contribute. 40 | 41 | [dart]: https://dart.dev 42 | [awesome-dart]: https://github.com/yissachar/awesome-dart 43 | [contributing]: https://github.com/dart-lang/samples/blob/main/CONTRIBUTING.md 44 | [pop-pop-win]: https://github.com/dart-lang/sample-pop_pop_win 45 | [dart-tutorials]: https://dart.dev/tutorials 46 | -------------------------------------------------------------------------------- /command_line/lib/github_activity.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'dart:io'; 6 | 7 | import 'package:github/github.dart'; 8 | 9 | import 'src/formatter.dart'; 10 | import 'src/options.dart'; 11 | import 'src/util.dart' as util; 12 | 13 | export 'src/options.dart'; 14 | 15 | /// Returns the value of the `GITHUB_TOKEN` environment variable. This 16 | /// variable should contain a GitHub auth token. Auth tokens are used to avoid 17 | /// API rate-limiting. 18 | Authentication get authentication { 19 | var ghStatsToken = Platform.environment['GITHUB_TOKEN']; 20 | if (ghStatsToken == null) { 21 | return Authentication.anonymous(); 22 | } 23 | return Authentication.withToken(ghStatsToken); 24 | } 25 | 26 | /// Returns the activity for a given GitHub user, formatted using the provided 27 | /// [formatter]. 28 | class ActivityService { 29 | final String username; 30 | final bool verbose; 31 | final Interval interval; 32 | final EventFormatter formatter; 33 | static const _supportedEventTypes = ['PullRequestEvent', 'IssuesEvent']; 34 | 35 | ActivityService( 36 | this.username, 37 | this.verbose, 38 | this.interval, { 39 | this.formatter = const DefaultEventFormatter(), 40 | }); 41 | 42 | /// Returns a stream of formatted lines for printing to the console. 43 | Stream getActivityStrings() async* { 44 | var stream = _fetchUserStatsImpl(); 45 | 46 | try { 47 | await for (var s in stream) { 48 | yield s; 49 | } 50 | } catch (e) { 51 | throw GetActivityException(username, e); 52 | } 53 | } 54 | 55 | Stream _fetchUserStatsImpl() async* { 56 | var client = GitHub(auth: authentication); 57 | var events = client.activity.listEventsPerformedByUser(username); 58 | 59 | await for (var event in events) { 60 | if (util.isTooOld(event.createdAt, interval)) { 61 | return; 62 | } 63 | 64 | if (_isSupported(event) || verbose) { 65 | yield formatter.format(event); 66 | } 67 | } 68 | } 69 | 70 | bool _isSupported(Event event) { 71 | return _supportedEventTypes.contains(event.type); 72 | } 73 | } 74 | 75 | /// Thrown when this package fails to get the user's activity 76 | class GetActivityException implements Exception { 77 | final String username; 78 | final Object original; 79 | 80 | GetActivityException(this.username, this.original); 81 | 82 | @override 83 | String toString() => 'failed to fetch stats for user $username: $original'; 84 | } 85 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | *See also: [Dart's code of conduct][code-of-conduct]* 3 | 4 | [code-of-conduct]: https://dart.dev/code-of-conduct 5 | 6 | ## Ways you can contribute 7 | 8 | - Give us feedback by [filing an issue][issues] 9 | - Fix an issue by [creating a pull request][pull-requests] 10 | - To contribute to the Dart SDK itself, see [this guide][dart-contributing] 11 | instead. 12 | 13 | Please do not submit your own samples to this project. If you have a sample you 14 | would like to share, let us know on our [community channels][community]. 15 | 16 | ## Before you contribute 17 | 18 | Before we can use your code, you must sign the [Google Individual Contributor 19 | License Agreement](https://cla.developers.google.com/about/google-individual) 20 | (CLA), which you can do online. The CLA is necessary mainly because you own the 21 | copyright to your changes, even after your contribution becomes part of our 22 | codebase, so we need your permission to use and distribute your code. We also 23 | need to be sure of various other things—for instance that you'll tell us if you 24 | know that your code infringes on other people's patents. You don't have to sign 25 | the CLA until after you've submitted your code for review and a member has 26 | approved it, but you must do it before we can put your code into our codebase. 27 | 28 | Before you start working on a larger contribution, you should get in touch with 29 | us first through the issue tracker with your idea so that we can help out and 30 | possibly guide you. Coordinating up front makes it much easier to avoid 31 | frustration later on. 32 | 33 | ## Coding style 34 | 35 | The source code in this project follows the: 36 | 37 | - [Google C++ style guide](https://google.github.io/styleguide/cppguide.html) 38 | - [Dart style guide](https://dart.dev/guides/language/effective-dart/style) 39 | 40 | You should familiarize yourself with those guidelines. 41 | 42 | All files in the Dart project must start with the following header. If you add a 43 | new file please also add this. The year should be a single number (not a range; 44 | don't use "2011-2012", even if the original code did). If you edit an existing 45 | file you don't have to update the year. 46 | 47 | ```dart 48 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 49 | // for details. All rights reserved. Use of this source code is governed by a 50 | // BSD-style license that can be found in the LICENSE file. 51 | ``` 52 | 53 | [dart-contributing]: https://github.com/dart-lang/sdk/blob/main/CONTRIBUTING.md 54 | [issues]: https://github.com/dart-lang/samples/issues 55 | [pull-requests]: https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request 56 | [community]: https://dart.dev/community 57 | -------------------------------------------------------------------------------- /isolates/bin/long_running_isolate.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | // Spawn an isolate, read multiple files, send their contents to the spawned 6 | // isolate, and wait for the parsed JSON. 7 | import 'dart:async'; 8 | import 'dart:convert'; 9 | import 'dart:io'; 10 | import 'dart:isolate'; 11 | 12 | import 'package:async/async.dart'; 13 | 14 | const filenames = ['json_01.json', 'json_02.json', 'json_03.json']; 15 | 16 | void main() async { 17 | await for (final jsonData in _sendAndReceive(filenames)) { 18 | print('Received JSON with ${jsonData.length} keys'); 19 | } 20 | } 21 | 22 | // Spawns an isolate and asynchronously sends a list of filenames for it to 23 | // read and decode. Waits for the response containing the decoded JSON 24 | // before sending the next. 25 | // 26 | // Returns a stream that emits the JSON-decoded contents of each file. 27 | Stream> _sendAndReceive(List filenames) async* { 28 | final p = ReceivePort(); 29 | await Isolate.spawn(_readAndParseJsonService, p.sendPort); 30 | 31 | // Convert the ReceivePort into a StreamQueue to receive messages from the 32 | // spawned isolate using a pull-based interface. Events are stored in this 33 | // queue until they are accessed by `events.next`. 34 | final events = StreamQueue(p); 35 | 36 | // The first message from the spawned isolate is a SendPort. This port is 37 | // used to communicate with the spawned isolate. 38 | SendPort sendPort = await events.next; 39 | 40 | for (var filename in filenames) { 41 | // Send the next filename to be read and parsed 42 | sendPort.send(filename); 43 | 44 | // Receive the parsed JSON 45 | Map message = await events.next; 46 | 47 | // Add the result to the stream returned by this async* function. 48 | yield message; 49 | } 50 | 51 | // Send a signal to the spawned isolate indicating that it should exit. 52 | sendPort.send(null); 53 | 54 | // Dispose the StreamQueue. 55 | await events.cancel(); 56 | } 57 | 58 | // The entrypoint that runs on the spawned isolate. Receives messages from 59 | // the main isolate, reads the contents of the file, decodes the JSON, and 60 | // sends the result back to the main isolate. 61 | Future _readAndParseJsonService(SendPort p) async { 62 | print('Spawned isolate started.'); 63 | 64 | // Send a SendPort to the main isolate so that it can send JSON strings to 65 | // this isolate. 66 | final commandPort = ReceivePort(); 67 | p.send(commandPort.sendPort); 68 | 69 | // Wait for messages from the main isolate. 70 | await for (final message in commandPort) { 71 | if (message is String) { 72 | // Read and decode the file. 73 | final contents = await File(message).readAsString(); 74 | 75 | // Send the result to the main isolate. 76 | p.send(jsonDecode(contents)); 77 | } else if (message == null) { 78 | // Exit if the main isolate sends a null message, indicating there are no 79 | // more files to read and parse. 80 | break; 81 | } 82 | } 83 | 84 | print('Spawned isolate finished.'); 85 | Isolate.exit(); 86 | } 87 | -------------------------------------------------------------------------------- /server/simple/bin/server.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'dart:convert'; 6 | import 'dart:io'; 7 | 8 | import 'package:shelf/shelf.dart'; 9 | import 'package:shelf/shelf_io.dart' as shelf_io; 10 | import 'package:shelf_router/shelf_router.dart' as shelf_router; 11 | import 'package:shelf_static/shelf_static.dart' as shelf_static; 12 | 13 | Future main() async { 14 | // If the "PORT" environment variable is set, listen to it. Otherwise, 8080. 15 | // https://cloud.google.com/run/docs/reference/container-contract#port 16 | final port = int.parse(Platform.environment['PORT'] ?? '8080'); 17 | 18 | // See https://pub.dev/documentation/shelf/latest/shelf/Cascade-class.html 19 | final cascade = Cascade() 20 | // First, serve files from the 'public' directory 21 | .add(_staticHandler) 22 | // If a corresponding file is not found, send requests to a `Router` 23 | .add(_router.call); 24 | 25 | // See https://pub.dev/documentation/shelf/latest/shelf_io/serve.html 26 | final server = await shelf_io.serve( 27 | // See https://pub.dev/documentation/shelf/latest/shelf/logRequests.html 28 | logRequests() 29 | // See https://pub.dev/documentation/shelf/latest/shelf/MiddlewareExtensions/addHandler.html 30 | .addHandler(cascade.handler), 31 | InternetAddress.anyIPv4, // Allows external connections 32 | port, 33 | ); 34 | 35 | print('Serving at http://${server.address.host}:${server.port}'); 36 | 37 | // Used for tracking uptime of the demo server. 38 | _watch.start(); 39 | } 40 | 41 | // Serve files from the file system. 42 | final _staticHandler = shelf_static.createStaticHandler( 43 | 'public', 44 | defaultDocument: 'index.html', 45 | ); 46 | 47 | // Router instance to handler requests. 48 | final _router = shelf_router.Router() 49 | ..get('/helloworld', _helloWorldHandler) 50 | ..get( 51 | '/time', 52 | (request) => Response.ok(DateTime.now().toUtc().toIso8601String()), 53 | ) 54 | ..get('/info.json', _infoHandler) 55 | ..get('/sum//', _sumHandler); 56 | 57 | Response _helloWorldHandler(Request request) => Response.ok('Hello, World!'); 58 | 59 | String _jsonEncode(Object? data) => 60 | const JsonEncoder.withIndent(' ').convert(data); 61 | 62 | const _jsonHeaders = {'content-type': 'application/json'}; 63 | 64 | Response _sumHandler(Request request, String a, String b) { 65 | final aNum = int.parse(a); 66 | final bNum = int.parse(b); 67 | return Response.ok( 68 | _jsonEncode({'a': aNum, 'b': bNum, 'sum': aNum + bNum}), 69 | headers: { 70 | ..._jsonHeaders, 71 | 'Cache-Control': 'public, max-age=604800, immutable', 72 | }, 73 | ); 74 | } 75 | 76 | final _watch = Stopwatch(); 77 | 78 | int _requestCount = 0; 79 | 80 | final _dartVersion = () { 81 | final version = Platform.version; 82 | return version.substring(0, version.indexOf(' ')); 83 | }(); 84 | 85 | Response _infoHandler(Request request) => Response( 86 | 200, 87 | headers: {..._jsonHeaders, 'Cache-Control': 'no-store'}, 88 | body: _jsonEncode({ 89 | 'Dart version': _dartVersion, 90 | 'uptime': _watch.elapsed.toString(), 91 | 'requestCount': ++_requestCount, 92 | }), 93 | ); 94 | -------------------------------------------------------------------------------- /ffi/primitives/primitives.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'dart:ffi'; 6 | import 'dart:io'; 7 | 8 | import 'package:ffi/ffi.dart'; 9 | import 'package:path/path.dart' as path; 10 | 11 | // C sum function - int sum(int a, int b); 12 | // 13 | // Example of how to pass parameters into C and use the returned result 14 | typedef SumFunc = Int32 Function(Int32 a, Int32 b); 15 | typedef Sum = int Function(int a, int b); 16 | 17 | // C subtract function - int subtract(int *a, int b); 18 | // 19 | // Example of how to create pointers in Dart, alloc them, and pass them as 20 | // parameters 21 | typedef SubtractFunc = Int32 Function(Pointer a, Int32 b); 22 | typedef Subtract = int Function(Pointer a, int b); 23 | 24 | // C multiply function - int *multiply(int a, int b); 25 | // 26 | // Example of how to receive pointers in Dart and access the data 27 | typedef MultiplyFunc = Pointer Function(Int32 a, Int32 b); 28 | typedef Multiply = Pointer Function(int a, int b); 29 | 30 | // C free function - void free_pointer(int *int_pointer); 31 | // 32 | // Example of how to free pointers that were allocated in C. 33 | typedef FreePointerFunc = Void Function(Pointer a); 34 | typedef FreePointer = void Function(Pointer a); 35 | 36 | void main() { 37 | // Open the dynamic library 38 | var libraryPath = path.join( 39 | Directory.current.path, 40 | 'primitives_library', 41 | 'libprimitives.so', 42 | ); 43 | if (Platform.isMacOS) { 44 | libraryPath = path.join( 45 | Directory.current.path, 46 | 'primitives_library', 47 | 'libprimitives.dylib', 48 | ); 49 | } 50 | if (Platform.isWindows) { 51 | libraryPath = path.join( 52 | Directory.current.path, 53 | 'primitives_library', 54 | 'Debug', 55 | 'primitives.dll', 56 | ); 57 | } 58 | 59 | final dylib = DynamicLibrary.open(libraryPath); 60 | 61 | // calls int sum(int a, int b); 62 | final sumPointer = dylib.lookup>('sum'); 63 | final sum = sumPointer.asFunction(); 64 | print('3 + 5 = ${sum(3, 5)}'); 65 | 66 | // calls int subtract(int *a, int b); 67 | // Create a pointer 68 | final p = calloc(); 69 | // Place a value into the address 70 | p.value = 3; 71 | 72 | final subtractPointer = dylib.lookup>( 73 | 'subtract', 74 | ); 75 | final subtract = subtractPointer.asFunction(); 76 | print('3 - 5 = ${subtract(p, 5)}'); 77 | 78 | // Free up allocated memory. 79 | calloc.free(p); 80 | 81 | // calls int *multiply(int a, int b); 82 | final multiplyPointer = dylib.lookup>( 83 | 'multiply', 84 | ); 85 | final multiply = multiplyPointer.asFunction(); 86 | final resultPointer = multiply(3, 5); 87 | // Fetch the result at the address pointed to 88 | final int result = resultPointer.value; 89 | print('3 * 5 = $result'); 90 | 91 | // Free up allocated memory. This time in C, because it was allocated in C. 92 | final freePointerPointer = dylib.lookup>( 93 | 'free_pointer', 94 | ); 95 | final freePointer = freePointerPointer.asFunction(); 96 | freePointer(resultPointer); 97 | } 98 | -------------------------------------------------------------------------------- /null_safety/calculate_lix/lib/lix.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Based on: 6 | /// https://readabilityformulas.com/the-LIX-readability-formula.php. 7 | class Lix { 8 | /// Number of words in general. 9 | int words; 10 | 11 | /// Number of words with more than 6 characters. 12 | int longWords; 13 | 14 | /// Number of periods. 15 | int periods; 16 | 17 | /// The calculated lix readability index. 18 | /// 19 | /// TIP: `readability` isn't passed to the constructor, but calculated. By 20 | /// adding the late keyword we tell the analyzer that it will be initialized 21 | /// later in the program. 22 | late int readability; 23 | 24 | /// TIP: Because the fields are all non-nullable, the constructor must 25 | /// initialize them all. We can either set a default value, or like here make 26 | /// the fields 'required', meaning that a value must be passed to the 27 | /// constructor. 'required' is a new keyword introduced as part of null safety 28 | /// which replaces the previous '@required' annotation. 29 | Lix({required this.words, required this.longWords, required this.periods}) { 30 | readability = _calculate(); 31 | } 32 | 33 | factory Lix.fromString(String text) { 34 | // Count periods: . : ; ! ? 35 | var periods = RegExp(r'[.:;!?]').allMatches(text).length; 36 | 37 | // Count words. 38 | // 39 | // TIP: We're using null safe versions of the core libraries, so it's clear 40 | // from the signature of split() that it returns a non-null result. 41 | var allWords = text.split(RegExp(r'\W+')); 42 | var words = allWords.length; 43 | var longWords = allWords.where((w) => w.length > 6).toList().length; 44 | 45 | return Lix(words: words, longWords: longWords, periods: periods); 46 | } 47 | 48 | /// TIP: Notice how we declare a non-nullable uninitialized `result` variable, 49 | /// yet we can return is as a non-nullable result without getting an error. 50 | /// 51 | /// This is possible due to "definite assignment": The Dart analyzer 52 | /// determines that a value has definitely been assigned before we return. Try 53 | /// removing the assignment to `result` in our of the if/else code branches, 54 | /// and notice how an error then appears in the return statement. 55 | int _calculate() { 56 | int result; 57 | 58 | if (words == 0 || periods == 0) { 59 | throw ArgumentError('Text must contain at least one full sentence.'); 60 | } else { 61 | final sentenceLength = words / periods; 62 | final wordLength = (longWords * 100) / words; 63 | result = (sentenceLength + wordLength).round(); 64 | } 65 | 66 | return result; 67 | } 68 | 69 | /// TIP: Notice how flow analysis knows that every branch returns a value for 70 | /// `readability` and so it's ok to have a non-nullable return type (try 71 | /// removing the last else-statement). 72 | String describe() { 73 | if (readability > 0 && readability < 20) { 74 | return 'very easy'; 75 | } else if (readability < 30) { 76 | return 'easy'; 77 | } else if (readability < 40) { 78 | return 'a little hard'; 79 | } else if (readability < 50) { 80 | return 'hard'; 81 | } else if (readability < 60) { 82 | return 'very hard'; 83 | } else { 84 | return 'unknown'; 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /parameters/lib/super_initalizer.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// This example shows the use of super-initializer parameters. 6 | /// 7 | /// Super-initializer parameters allow to forward constructor parameters 8 | /// to the superclass, avoiding having to write the parameter multiple times 9 | /// in the superclass constructor invocation. 10 | library; 11 | 12 | /// This example contains multiple classes representing different types of 13 | /// synthesizers, a musical instrument similar to a piano 14 | /// which can be used to create new sounds. 15 | /// 16 | /// All subclasses inherit from the [Synth] class and take advantage of the 17 | /// different super-initializer capabilities. 18 | class Synth { 19 | /// Model name 20 | final String model; 21 | 22 | /// Amount of notes that can be played at the same time 23 | final int polyphony; 24 | 25 | /// Amount of sound generators, default to 1 26 | final int oscillators; 27 | 28 | /// In the class constructor [model] is a positional parameter, 29 | /// while [polyphony] and [oscillators] are named parameters. 30 | Synth(this.model, {required this.polyphony, this.oscillators = 1}); 31 | 32 | @override 33 | String toString() { 34 | return 'Synth $model. Polyphony: $polyphony, oscillators: $oscillators'; 35 | } 36 | } 37 | 38 | /// This class represents an old vintage synthesizer. 39 | /// 40 | /// [VintageSynth] can only have 1 oscillator. 41 | /// [polyphony] is optional and is 1 by default. 42 | class VintageSynth extends Synth { 43 | /// [model] is forwarded to the super constructor. 44 | /// Named parameter [polyphony] is forwarded, with the default value of 1. 45 | VintageSynth(super.model, {super.polyphony = 1}); 46 | } 47 | 48 | /// This class represents a modern digital synthesizer. 49 | /// 50 | /// [DigitalSynth] can only have 1 oscillator. 51 | /// Named parameter [polyphony] is required. 52 | class DigitalSynth extends Synth { 53 | /// [model] is forwarded to the super constructor. 54 | /// Named parameter [polyphony] is forwarded and it is required. 55 | DigitalSynth(super.model, {required super.polyphony}); 56 | 57 | /// The following constructor declaration would not be possible 58 | /// because [polyphony] is not a positional argument. 59 | /// 60 | /// DigitalSynth(super.model, super.polyphony); 61 | } 62 | 63 | /// This class represents a complex multi-oscillator synthesizer. 64 | /// 65 | /// [MultiOscillator] requires all three parameters. 66 | class MultiOscillatorSynth extends Synth { 67 | /// This constructor has three positional parameters instead of one. 68 | /// 69 | /// [model] is forwarded to the super constructor. 70 | /// [polyphony] and [oscillators] positional parameters are then passed to the 71 | /// named parameters in the super constructor. 72 | MultiOscillatorSynth(super.model, int polyphony, int oscillators) 73 | : super(polyphony: polyphony, oscillators: oscillators); 74 | } 75 | 76 | /// This class represents a synth with a fixed amount 77 | /// of polyphony and oscillators. 78 | /// 79 | /// [FixedOscillatorSynth] only requires the positional parameter [model]. 80 | class FixedOscillatorSynth extends Synth { 81 | /// [model] is forwarded to the super constructor. 82 | /// [polyphony] and [oscillators] are hardcoded. 83 | FixedOscillatorSynth(super.model) : super(polyphony: 1, oscillators: 3); 84 | } 85 | -------------------------------------------------------------------------------- /tool/ci.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Created with package:mono_repo v6.6.3 3 | 4 | # Support built in commands on windows out of the box. 5 | 6 | # When it is a flutter repo (check the pubspec.yaml for "sdk: flutter") 7 | # then "flutter pub" is called instead of "dart pub". 8 | # This assumes that the Flutter SDK has been installed in a previous step. 9 | function pub() { 10 | if grep -Fq "sdk: flutter" "${PWD}/pubspec.yaml"; then 11 | command flutter pub "$@" 12 | else 13 | command dart pub "$@" 14 | fi 15 | } 16 | 17 | function format() { 18 | command dart format "$@" 19 | } 20 | 21 | # When it is a flutter repo (check the pubspec.yaml for "sdk: flutter") 22 | # then "flutter analyze" is called instead of "dart analyze". 23 | # This assumes that the Flutter SDK has been installed in a previous step. 24 | function analyze() { 25 | if grep -Fq "sdk: flutter" "${PWD}/pubspec.yaml"; then 26 | command flutter analyze "$@" 27 | else 28 | command dart analyze "$@" 29 | fi 30 | } 31 | 32 | if [[ -z ${PKGS} ]]; then 33 | echo -e '\033[31mPKGS environment variable must be set! - TERMINATING JOB\033[0m' 34 | exit 64 35 | fi 36 | 37 | if [[ "$#" == "0" ]]; then 38 | echo -e '\033[31mAt least one task argument must be provided! - TERMINATING JOB\033[0m' 39 | exit 64 40 | fi 41 | 42 | SUCCESS_COUNT=0 43 | declare -a FAILURES 44 | 45 | for PKG in ${PKGS}; do 46 | echo -e "\033[1mPKG: ${PKG}\033[22m" 47 | EXIT_CODE=0 48 | pushd "${PKG}" >/dev/null || EXIT_CODE=$? 49 | 50 | if [[ ${EXIT_CODE} -ne 0 ]]; then 51 | echo -e "\033[31mPKG: '${PKG}' does not exist - TERMINATING JOB\033[0m" 52 | exit 64 53 | fi 54 | 55 | dart pub upgrade || EXIT_CODE=$? 56 | 57 | if [[ ${EXIT_CODE} -ne 0 ]]; then 58 | echo -e "\033[31mPKG: ${PKG}; 'dart pub upgrade' - FAILED (${EXIT_CODE})\033[0m" 59 | FAILURES+=("${PKG}; 'dart pub upgrade'") 60 | else 61 | for TASK in "$@"; do 62 | EXIT_CODE=0 63 | echo 64 | echo -e "\033[1mPKG: ${PKG}; TASK: ${TASK}\033[22m" 65 | case ${TASK} in 66 | analyze) 67 | echo 'dart analyze --fatal-infos .' 68 | dart analyze --fatal-infos . || EXIT_CODE=$? 69 | ;; 70 | format) 71 | echo 'dart format --output=none --set-exit-if-changed .' 72 | dart format --output=none --set-exit-if-changed . || EXIT_CODE=$? 73 | ;; 74 | test) 75 | echo 'dart test' 76 | dart test || EXIT_CODE=$? 77 | ;; 78 | test_with_coverage) 79 | echo 'dart pub global run coverage:test_with_coverage' 80 | dart pub global run coverage:test_with_coverage || EXIT_CODE=$? 81 | ;; 82 | *) 83 | echo -e "\033[31mUnknown TASK '${TASK}' - TERMINATING JOB\033[0m" 84 | exit 64 85 | ;; 86 | esac 87 | 88 | if [[ ${EXIT_CODE} -ne 0 ]]; then 89 | echo -e "\033[31mPKG: ${PKG}; TASK: ${TASK} - FAILED (${EXIT_CODE})\033[0m" 90 | FAILURES+=("${PKG}; TASK: ${TASK}") 91 | else 92 | echo -e "\033[32mPKG: ${PKG}; TASK: ${TASK} - SUCCEEDED\033[0m" 93 | SUCCESS_COUNT=$((SUCCESS_COUNT + 1)) 94 | fi 95 | 96 | done 97 | fi 98 | 99 | echo 100 | echo -e "\033[32mSUCCESS COUNT: ${SUCCESS_COUNT}\033[0m" 101 | 102 | if [ ${#FAILURES[@]} -ne 0 ]; then 103 | echo -e "\033[31mFAILURES: ${#FAILURES[@]}\033[0m" 104 | for i in "${FAILURES[@]}"; do 105 | echo -e "\033[31m $i\033[0m" 106 | done 107 | fi 108 | 109 | popd >/dev/null || exit 70 110 | echo 111 | done 112 | 113 | if [ ${#FAILURES[@]} -ne 0 ]; then 114 | exit 1 115 | fi 116 | -------------------------------------------------------------------------------- /ffi/structs/structs.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'dart:ffi'; 6 | import 'dart:io' show Directory, Platform; 7 | 8 | import 'package:ffi/ffi.dart'; 9 | import 'package:path/path.dart' as path; 10 | 11 | // Example of handling a simple C struct 12 | final class Coordinate extends Struct { 13 | @Double() 14 | external double latitude; 15 | 16 | @Double() 17 | external double longitude; 18 | } 19 | 20 | // Example of a complex struct (contains a string and a nested struct) 21 | final class Place extends Struct { 22 | external Pointer name; 23 | 24 | external Coordinate coordinate; 25 | } 26 | 27 | // C function: char *hello_world(); 28 | // There's no need for two typedefs here, as both the 29 | // C and Dart functions have the same signature 30 | typedef HelloWorld = Pointer Function(); 31 | 32 | // C function: char *reverse(char *str, int length) 33 | typedef ReverseNative = Pointer Function(Pointer str, Int32 length); 34 | typedef Reverse = Pointer Function(Pointer str, int length); 35 | 36 | // C function: void free_string(char *str) 37 | typedef FreeStringNative = Void Function(Pointer str); 38 | typedef FreeString = void Function(Pointer str); 39 | 40 | // C function: struct Coordinate create_coordinate(double latitude, double longitude) 41 | typedef CreateCoordinateNative = 42 | Coordinate Function(Double latitude, Double longitude); 43 | typedef CreateCoordinate = 44 | Coordinate Function(double latitude, double longitude); 45 | 46 | // C function: struct Place create_place(char *name, double latitude, double longitude) 47 | typedef CreatePlaceNative = 48 | Place Function(Pointer name, Double latitude, Double longitude); 49 | typedef CreatePlace = 50 | Place Function(Pointer name, double latitude, double longitude); 51 | 52 | typedef DistanceNative = Double Function(Coordinate p1, Coordinate p2); 53 | typedef Distance = double Function(Coordinate p1, Coordinate p2); 54 | 55 | void main() { 56 | // Open the dynamic library 57 | var libraryPath = path.join( 58 | Directory.current.path, 59 | 'structs_library', 60 | 'libstructs.so', 61 | ); 62 | if (Platform.isMacOS) { 63 | libraryPath = path.join( 64 | Directory.current.path, 65 | 'structs_library', 66 | 'libstructs.dylib', 67 | ); 68 | } 69 | if (Platform.isWindows) { 70 | libraryPath = path.join( 71 | Directory.current.path, 72 | 'structs_library', 73 | 'Debug', 74 | 'structs.dll', 75 | ); 76 | } 77 | final dylib = DynamicLibrary.open(libraryPath); 78 | 79 | final helloWorld = dylib.lookupFunction( 80 | 'hello_world', 81 | ); 82 | final message = helloWorld().toDartString(); 83 | print(message); 84 | 85 | final reverse = dylib.lookupFunction('reverse'); 86 | final backwards = 'backwards'; 87 | final backwardsUtf8 = backwards.toNativeUtf8(); 88 | final reversedMessageUtf8 = reverse(backwardsUtf8, backwards.length); 89 | final reversedMessage = reversedMessageUtf8.toDartString(); 90 | calloc.free(backwardsUtf8); 91 | print('$backwards reversed is $reversedMessage'); 92 | 93 | final freeString = dylib.lookupFunction( 94 | 'free_string', 95 | ); 96 | freeString(reversedMessageUtf8); 97 | 98 | final createCoordinate = dylib 99 | .lookupFunction( 100 | 'create_coordinate', 101 | ); 102 | final coordinate = createCoordinate(3.5, 4.6); 103 | print( 104 | 'Coordinate is lat ${coordinate.latitude}, long ${coordinate.longitude}', 105 | ); 106 | 107 | final myHomeUtf8 = 'My Home'.toNativeUtf8(); 108 | final createPlace = dylib.lookupFunction( 109 | 'create_place', 110 | ); 111 | final place = createPlace(myHomeUtf8, 42.0, 24.0); 112 | final name = place.name.toDartString(); 113 | calloc.free(myHomeUtf8); 114 | final coord = place.coordinate; 115 | print( 116 | 'The name of my place is $name at ${coord.latitude}, ${coord.longitude}', 117 | ); 118 | final distance = dylib.lookupFunction('distance'); 119 | final dist = distance(createCoordinate(2.0, 2.0), createCoordinate(5.0, 6.0)); 120 | print("distance between (2,2) and (5,6) = $dist"); 121 | } 122 | -------------------------------------------------------------------------------- /package_constraint_solver/lib/constraint_solver.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2023, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// A constraint has a list of variables it constrains and 6 | /// a method that checks whether it is satisfied. 7 | abstract class Constraint { 8 | final List variables; 9 | 10 | Constraint(this.variables); 11 | 12 | bool isSatisfied(Map assignment); 13 | } 14 | 15 | /// An instance of a constraint satisfaction problem. 16 | /// 17 | /// A CSP framework is modeled as a set of _variables_ that can be assigned 18 | /// within a range called a _domain_. 19 | /// 20 | /// ```dart 21 | /// var doug = Guest('Doug', dislikes: ['artichoke']); 22 | /// var patrick = Guest('Patrick', dislikes: ['bananas']); 23 | /// var susan = Guest('Susan', dislikes: ['broccoli']); 24 | /// var variables = [doug, patrick, susan]; 25 | /// 26 | /// var meals = ['artichoke', 'bananas', 'broccoli']; 27 | /// 28 | /// var domains = { 29 | /// doug: meals, 30 | /// patrick: meals, 31 | /// susan: meals, 32 | /// }; 33 | /// 34 | /// var csp = CSP(variables, domains); 35 | /// 36 | /// csp.addConstraint(AvoidDislikes(variables)); 37 | /// 38 | /// var result = csp.backtrackingSearch(); 39 | /// print(result); 40 | /// ``` 41 | /// 42 | class CSP { 43 | final List variables; 44 | final Map> domains; 45 | final Map>> constraints = {}; 46 | 47 | /// Creates an instance of a constraint satisfaction problem. 48 | /// 49 | /// Each variable in the [variables] list must be a key in the [domains] map. 50 | CSP(this.variables, this.domains) { 51 | for (var variable in variables) { 52 | // Add an entry for each variable to the constraints map 53 | constraints[variable] = []; 54 | 55 | // Check that each variable is present in the domains map 56 | if (!domains.containsKey(variable)) { 57 | throw ArgumentError( 58 | 'Each variable should have a domain associated with it.', 59 | ); 60 | } 61 | } 62 | } 63 | 64 | /// Adds a constraint to be used when finding a solution. 65 | void addConstraint(Constraint constraint) { 66 | for (var variable in constraint.variables) { 67 | // Check that this constraint's variable is present in this CSP 68 | if (!variables.contains(variable)) { 69 | throw ArgumentError( 70 | "The constraint's variable is not present in this CSP", 71 | ); 72 | } 73 | 74 | // Add the constraint to the `constraints` map. As long as the previous 75 | // check succeeded, an entry will exist, so it's safe to cast it to a 76 | // non-nullable type. 77 | constraints[variable]!.add(constraint); 78 | } 79 | } 80 | 81 | /// Checks whether the value assignment is consistent by checking it against 82 | /// all constraints for the given variable. 83 | bool isConsistent(V variable, Map assignment) { 84 | for (var constraint in constraints[variable]!) { 85 | if (!constraint.isSatisfied(assignment)) { 86 | return false; 87 | } 88 | } 89 | 90 | return true; 91 | } 92 | 93 | /// Runs a recursive backtracking search for a solution that satisfies all of 94 | /// the constraints. The constraints are satisfied when isConsistent returns 95 | /// true. 96 | /// 97 | /// This algorithm is similar to a depth-first search and has a time 98 | /// complexity of O(V) where V is the number of possible assignments. 99 | Map? backtrackingSearch([Map assignment = const {}]) { 100 | // If every variable is assigned, the search is complete. 101 | if (assignment.length == variables.length) { 102 | return assignment; 103 | } 104 | // Get the first variable in the CSP but not in the assignment. 105 | V unassigned = variables.firstWhere((v) => !assignment.containsKey(v)); 106 | 107 | // Look through every domain value of the first unassigned variable 108 | for (var value in domains[unassigned]!) { 109 | // Create a shallow copy of assignment to modify 110 | final localAssignment = Map.from(assignment); 111 | localAssignment[unassigned] = value; 112 | 113 | if (isConsistent(unassigned, localAssignment)) { 114 | final result = backtrackingSearch(localAssignment); 115 | if (result != null) { 116 | return result; 117 | } 118 | } 119 | } 120 | return null; 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /package_constraint_solver/example/scheduler_example.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2023, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'package:constraint_solver/constraint_solver.dart'; 6 | import 'package:intl/intl.dart'; 7 | 8 | final dateFormat = DateFormat.yMEd().add_jms(); 9 | 10 | // A scheduling problem, where the variables are a user's tasks, 11 | // and the domain is the times where the user is available. 12 | void main() { 13 | final tasks = [ 14 | Task('Feed the dogs', Duration(minutes: 15)), 15 | Task('Work on highlight', Duration(minutes: 15)), 16 | Task('Eat breakfast', Duration(minutes: 30)), 17 | ]; 18 | 19 | final timeSlots = [ 20 | TimeSlot(DateTime(2023, 2, 14, 8), DateTime(2023, 2, 14, 9)), 21 | TimeSlot(DateTime(2023, 2, 14, 11), DateTime(2023, 2, 14, 12)), 22 | ]; 23 | 24 | final scheduledTasks = scheduleTasks(tasks, timeSlots); 25 | 26 | for (var task in scheduledTasks.keys) { 27 | final startTime = scheduledTasks[task]; 28 | if (startTime == null) { 29 | throw ('Unexpected null value in map: $scheduledTasks'); 30 | } 31 | print('$task: ${dateFormat.format(startTime)}'); 32 | } 33 | } 34 | 35 | Map scheduleTasks(List tasks, List timeSlots) { 36 | final domains = >{}; 37 | 38 | // Any task can be scheduled into any time slot: 39 | for (var task in tasks) { 40 | domains[task] = timeSlots; 41 | } 42 | 43 | final csp = CSP(tasks, domains); 44 | 45 | csp.addConstraint(TaskConstraint(tasks)); 46 | 47 | final result = csp.backtrackingSearch(); 48 | 49 | if (result == null) { 50 | throw ('The tasks could not be scheduled in the provided time slots.'); 51 | } 52 | 53 | // Assign an actual time to schedule each task in the time slot. For example, 54 | // If there are two 30 minute tasks in a 60 minute time slot, one should be 55 | // scheduled at the start of the hour and the other at the 30-minute mark. 56 | 57 | // The time each task should be scheduled at. 58 | Map scheduledTasks = {}; 59 | // The amount of time that has been scheduled in a TimeSlot, used to determine 60 | // the time for the next task in the time slot. 61 | Map scheduledTimeInTimeSlots = {}; 62 | for (var timeSlot in timeSlots) { 63 | scheduledTimeInTimeSlots[timeSlot] = Duration(minutes: 0); 64 | } 65 | 66 | for (var entry in result.entries) { 67 | final task = entry.key; 68 | 69 | final timeSlot = entry.value; 70 | final scheduledTimeInTimeSlot = scheduledTimeInTimeSlots[timeSlot]; 71 | if (scheduledTimeInTimeSlot == null) { 72 | throw ('Unexpected null value in map: $scheduledTimeInTimeSlot'); 73 | } 74 | scheduledTasks[task] = timeSlot.start.add(scheduledTimeInTimeSlot); 75 | scheduledTimeInTimeSlots[timeSlot] = 76 | scheduledTimeInTimeSlot + task.duration; 77 | } 78 | 79 | return scheduledTasks; 80 | } 81 | 82 | class Task { 83 | final String name; 84 | final Duration duration; 85 | 86 | Task(this.name, this.duration); 87 | 88 | @override 89 | String toString() => '$name (${duration.inMinutes}m)'; 90 | } 91 | 92 | class TimeSlot { 93 | final DateTime start; 94 | final DateTime end; 95 | 96 | TimeSlot(this.start, this.end); 97 | 98 | Duration get duration => end.difference(start); 99 | 100 | @override 101 | String toString() => '($start, $end)'; 102 | } 103 | 104 | class TaskConstraint extends Constraint { 105 | TaskConstraint(super.variables); 106 | 107 | @override 108 | bool isSatisfied(Map assignment) { 109 | // Create a map containing the remaining time for each time slot 110 | Map remainingTime = {}; 111 | for (var timeSlot in assignment.values) { 112 | remainingTime[timeSlot] = Duration( 113 | milliseconds: timeSlot.duration.inMilliseconds, 114 | ); 115 | } 116 | 117 | // Check that each task fits in the available time slot. 118 | for (var task in assignment.keys) { 119 | final timeSlot = assignment[task]!; 120 | final remainingTimeInTimeSlot = remainingTime[timeSlot]; 121 | 122 | if (remainingTimeInTimeSlot == null) { 123 | return false; 124 | } 125 | 126 | // If there's not enough time remaining, this is not a valid assignment. 127 | if (remainingTimeInTimeSlot < task.duration) { 128 | return false; 129 | } 130 | 131 | // Subtract the task's time from the remaining time in the time slot. 132 | remainingTime[timeSlot] = remainingTimeInTimeSlot - task.duration; 133 | } 134 | 135 | return true; 136 | } 137 | } 138 | --------------------------------------------------------------------------------