├── .gitignore
├── .metadata
├── README.md
├── analysis_options.yaml
├── android
├── .gitignore
├── app
│ ├── build.gradle
│ └── src
│ │ ├── debug
│ │ └── AndroidManifest.xml
│ │ ├── main
│ │ ├── AndroidManifest.xml
│ │ ├── kotlin
│ │ │ └── com
│ │ │ │ └── example
│ │ │ │ └── flutter_ui_examples
│ │ │ │ └── MainActivity.kt
│ │ └── res
│ │ │ ├── drawable-v21
│ │ │ └── launch_background.xml
│ │ │ ├── drawable
│ │ │ └── launch_background.xml
│ │ │ ├── mipmap-hdpi
│ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-mdpi
│ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xhdpi
│ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ └── ic_launcher.png
│ │ │ ├── values-night
│ │ │ └── styles.xml
│ │ │ └── values
│ │ │ └── styles.xml
│ │ └── profile
│ │ └── AndroidManifest.xml
├── build.gradle
├── gradle.properties
├── gradle
│ └── wrapper
│ │ └── gradle-wrapper.properties
└── settings.gradle
├── assets
└── 6392956.jpg
├── calculate.sh
├── i18n
├── .gitignore
├── .metadata
├── lib
│ ├── i18n.dart
│ ├── strings.g.dart
│ ├── strings.i18n.json
│ ├── strings_de.i18n.json
│ └── strings_ru.i18n.json
└── pubspec.yaml
├── integration_test
├── elements_test.dart
├── keyed_list_view_scrolling_test.dart
└── prototyped_list_view_scrolling_test.dart
├── ios
├── .gitignore
├── Flutter
│ ├── AppFrameworkInfo.plist
│ ├── Debug.xcconfig
│ └── Release.xcconfig
├── Podfile
├── Podfile.lock
├── Runner.xcodeproj
│ ├── project.pbxproj
│ ├── project.xcworkspace
│ │ ├── contents.xcworkspacedata
│ │ └── xcshareddata
│ │ │ ├── IDEWorkspaceChecks.plist
│ │ │ └── WorkspaceSettings.xcsettings
│ └── xcshareddata
│ │ └── xcschemes
│ │ └── Runner.xcscheme
├── Runner.xcworkspace
│ ├── contents.xcworkspacedata
│ └── xcshareddata
│ │ ├── IDEWorkspaceChecks.plist
│ │ └── WorkspaceSettings.xcsettings
├── Runner
│ ├── AppDelegate.swift
│ ├── Assets.xcassets
│ │ ├── AppIcon.appiconset
│ │ │ ├── Contents.json
│ │ │ ├── Icon-App-1024x1024@1x.png
│ │ │ ├── Icon-App-20x20@1x.png
│ │ │ ├── Icon-App-20x20@2x.png
│ │ │ ├── Icon-App-20x20@3x.png
│ │ │ ├── Icon-App-29x29@1x.png
│ │ │ ├── Icon-App-29x29@2x.png
│ │ │ ├── Icon-App-29x29@3x.png
│ │ │ ├── Icon-App-40x40@1x.png
│ │ │ ├── Icon-App-40x40@2x.png
│ │ │ ├── Icon-App-40x40@3x.png
│ │ │ ├── Icon-App-60x60@2x.png
│ │ │ ├── Icon-App-60x60@3x.png
│ │ │ ├── Icon-App-76x76@1x.png
│ │ │ ├── Icon-App-76x76@2x.png
│ │ │ └── Icon-App-83.5x83.5@2x.png
│ │ └── LaunchImage.imageset
│ │ │ ├── Contents.json
│ │ │ ├── LaunchImage.png
│ │ │ ├── LaunchImage@2x.png
│ │ │ ├── LaunchImage@3x.png
│ │ │ └── README.md
│ ├── Base.lproj
│ │ ├── LaunchScreen.storyboard
│ │ └── Main.storyboard
│ ├── Info.plist
│ └── Runner-Bridging-Header.h
└── RunnerTests
│ └── RunnerTests.swift
├── lib
├── 10_media_query
│ └── media_query_example.dart
├── 11_deferred_indexed_stack
│ └── deferred_indexed_stack_example.dart
├── 12_gestures
│ ├── custom_button.dart
│ ├── custom_scale_detector.dart
│ ├── custom_scale_detector_2.dart
│ ├── custom_tap_detector.dart
│ ├── gestures_page.dart
│ ├── pan_detector.dart
│ ├── tap_pan_button.dart
│ └── transform_scale_detector.dart
├── 1_tap_effects
│ ├── tap_area.dart
│ └── tap_area_example.dart
├── 2_adaptive_refresh_indicator
│ ├── adaptive_refresh_indicator.dart
│ └── adaptive_refresh_indicator_example.dart
├── 2_adaptive_refresh_indicator_advanced
│ ├── adaptive_refresh_indicator.dart
│ └── adaptive_refresh_indicator_example.dart
├── 3_list_view_mistakes
│ ├── list_view_extent.dart
│ ├── list_view_keys.dart
│ ├── list_view_never_scrollable_slivers.dart
│ └── list_view_padding.dart
├── 4_text_scaling
│ └── text_scaling.dart
├── 5_localization
│ └── localization_example.dart
├── 6_widget_state_property
│ ├── card_example.dart
│ ├── selectable_button.dart
│ ├── tap_area_2.dart
│ └── widget_state_property_example.dart
├── 7_images
│ ├── images_example.dart
│ └── images_example_list.dart
├── 8_shapes
│ ├── shapes_example.dart
│ └── ticket_item.dart
├── 9_layers
│ └── layers_example.dart
└── main.dart
├── linux
├── .gitignore
├── CMakeLists.txt
├── flutter
│ ├── CMakeLists.txt
│ ├── generated_plugin_registrant.cc
│ ├── generated_plugin_registrant.h
│ └── generated_plugins.cmake
├── main.cc
├── my_application.cc
└── my_application.h
├── macos
├── .gitignore
├── Flutter
│ ├── Flutter-Debug.xcconfig
│ ├── Flutter-Release.xcconfig
│ └── GeneratedPluginRegistrant.swift
├── Podfile
├── Runner.xcodeproj
│ ├── project.pbxproj
│ ├── project.xcworkspace
│ │ └── xcshareddata
│ │ │ └── IDEWorkspaceChecks.plist
│ └── xcshareddata
│ │ └── xcschemes
│ │ └── Runner.xcscheme
├── Runner.xcworkspace
│ ├── contents.xcworkspacedata
│ └── xcshareddata
│ │ └── IDEWorkspaceChecks.plist
├── Runner
│ ├── AppDelegate.swift
│ ├── Assets.xcassets
│ │ └── AppIcon.appiconset
│ │ │ ├── Contents.json
│ │ │ ├── app_icon_1024.png
│ │ │ ├── app_icon_128.png
│ │ │ ├── app_icon_16.png
│ │ │ ├── app_icon_256.png
│ │ │ ├── app_icon_32.png
│ │ │ ├── app_icon_512.png
│ │ │ └── app_icon_64.png
│ ├── Base.lproj
│ │ └── MainMenu.xib
│ ├── Configs
│ │ ├── AppInfo.xcconfig
│ │ ├── Debug.xcconfig
│ │ ├── Release.xcconfig
│ │ └── Warnings.xcconfig
│ ├── DebugProfile.entitlements
│ ├── Info.plist
│ ├── MainFlutterWindow.swift
│ └── Release.entitlements
└── RunnerTests
│ └── RunnerTests.swift
├── pubspec.lock
├── pubspec.yaml
├── slang.yaml
├── test_driver
└── perf_driver.dart
├── web
├── favicon.png
├── icons
│ ├── Icon-192.png
│ ├── Icon-512.png
│ ├── Icon-maskable-192.png
│ └── Icon-maskable-512.png
├── index.html
└── manifest.json
└── windows
├── .gitignore
├── CMakeLists.txt
├── flutter
├── CMakeLists.txt
├── generated_plugin_registrant.cc
├── generated_plugin_registrant.h
└── generated_plugins.cmake
└── runner
├── CMakeLists.txt
├── Runner.rc
├── flutter_window.cpp
├── flutter_window.h
├── main.cpp
├── resource.h
├── resources
└── app_icon.ico
├── runner.exe.manifest
├── utils.cpp
├── utils.h
├── win32_window.cpp
└── win32_window.h
/.gitignore:
--------------------------------------------------------------------------------
1 | # Miscellaneous
2 | *.class
3 | *.log
4 | *.pyc
5 | *.swp
6 | .DS_Store
7 | .atom/
8 | .buildlog/
9 | .history
10 | .svn/
11 | migrate_working_dir/
12 |
13 | # IntelliJ related
14 | *.iml
15 | *.ipr
16 | *.iws
17 | .idea/
18 |
19 | # The .vscode folder contains launch configuration and tasks you configure in
20 | # VS Code which you may wish to be included in version control, so this line
21 | # is commented out by default.
22 | #.vscode/
23 |
24 | # Flutter/Dart/Pub related
25 | **/doc/api/
26 | **/ios/Flutter/.last_build_id
27 | .dart_tool/
28 | .flutter-plugins
29 | .flutter-plugins-dependencies
30 | .pub-cache/
31 | .pub/
32 | /build/
33 |
34 | # Symbolication related
35 | app.*.symbols
36 |
37 | # Obfuscation related
38 | app.*.map.json
39 |
40 | # Android Studio will place build artifacts here
41 | /android/app/debug
42 | /android/app/profile
43 | /android/app/release
44 |
--------------------------------------------------------------------------------
/.metadata:
--------------------------------------------------------------------------------
1 | # This file tracks properties of this Flutter project.
2 | # Used by Flutter tool to assess capabilities and perform upgrades etc.
3 | #
4 | # This file should be version controlled and should not be manually edited.
5 |
6 | version:
7 | revision: "b0366e0a3f089e15fd89c97604ab402fe26b724c"
8 | channel: "stable"
9 |
10 | project_type: app
11 |
12 | # Tracks metadata for the flutter migrate command
13 | migration:
14 | platforms:
15 | - platform: root
16 | create_revision: b0366e0a3f089e15fd89c97604ab402fe26b724c
17 | base_revision: b0366e0a3f089e15fd89c97604ab402fe26b724c
18 | - platform: android
19 | create_revision: b0366e0a3f089e15fd89c97604ab402fe26b724c
20 | base_revision: b0366e0a3f089e15fd89c97604ab402fe26b724c
21 | - platform: ios
22 | create_revision: b0366e0a3f089e15fd89c97604ab402fe26b724c
23 | base_revision: b0366e0a3f089e15fd89c97604ab402fe26b724c
24 | - platform: linux
25 | create_revision: b0366e0a3f089e15fd89c97604ab402fe26b724c
26 | base_revision: b0366e0a3f089e15fd89c97604ab402fe26b724c
27 | - platform: macos
28 | create_revision: b0366e0a3f089e15fd89c97604ab402fe26b724c
29 | base_revision: b0366e0a3f089e15fd89c97604ab402fe26b724c
30 | - platform: web
31 | create_revision: b0366e0a3f089e15fd89c97604ab402fe26b724c
32 | base_revision: b0366e0a3f089e15fd89c97604ab402fe26b724c
33 | - platform: windows
34 | create_revision: b0366e0a3f089e15fd89c97604ab402fe26b724c
35 | base_revision: b0366e0a3f089e15fd89c97604ab402fe26b724c
36 |
37 | # User provided section
38 |
39 | # List of Local paths (relative to this file) that should be
40 | # ignored by the migrate tool.
41 | #
42 | # Files that are not part of the templates will be ignored by default.
43 | unmanaged_files:
44 | - 'lib/main.dart'
45 | - 'ios/Runner.xcodeproj/project.pbxproj'
46 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | A repository with examples for Medium article series
2 |
3 | Part 1: https://medium.com/@pomis172/making-flutter-apps-look-more-native-part-1-tap-effects-48a59cb158bf
4 | Part 2: https://medium.com/@pomis172/making-flutter-apps-look-more-native-part-2-refresh-indicators-a747cefc496b?postPublishedType=initial
5 |
6 |
7 | ```
8 | ./calculate.sh average_frame_build_time_millis worst_frame_build_time_millis average_frame_rasterizer_time_millis worst_frame_rasterizer_time_millis
9 | ```
10 |
11 | ```
12 | flutter drive \
13 | --driver=test_driver/perf_driver.dart \
14 | --target=integration_test/prototyped_list_view_scrolling_test.dart \
15 | --profile \
16 | --no-dds
17 | ```
18 |
--------------------------------------------------------------------------------
/analysis_options.yaml:
--------------------------------------------------------------------------------
1 | # This file configures the analyzer, which statically analyzes Dart code to
2 | # check for errors, warnings, and lints.
3 | #
4 | # The issues identified by the analyzer are surfaced in the UI of Dart-enabled
5 | # IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be
6 | # invoked from the command line by running `flutter analyze`.
7 |
8 | # The following line activates a set of recommended lints for Flutter apps,
9 | # packages, and plugins designed to encourage good coding practices.
10 | include: package:flutter_lints/flutter.yaml
11 |
12 | linter:
13 | # The lint rules applied to this project can be customized in the
14 | # section below to disable rules from the `package:flutter_lints/flutter.yaml`
15 | # included above or to enable additional rules. A list of all available lints
16 | # and their documentation is published at https://dart.dev/lints.
17 | #
18 | # Instead of disabling a lint rule for the entire project in the
19 | # section below, it can also be suppressed for a single line of code
20 | # or a specific dart file by using the `// ignore: name_of_lint` and
21 | # `// ignore_for_file: name_of_lint` syntax on the line or in the file
22 | # producing the lint.
23 | rules:
24 | # avoid_print: false # Uncomment to disable the `avoid_print` rule
25 | # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule
26 |
27 | # Additional information about this file can be found at
28 | # https://dart.dev/guides/language/analysis-options
29 |
--------------------------------------------------------------------------------
/android/.gitignore:
--------------------------------------------------------------------------------
1 | gradle-wrapper.jar
2 | /.gradle
3 | /captures/
4 | /gradlew
5 | /gradlew.bat
6 | /local.properties
7 | GeneratedPluginRegistrant.java
8 |
9 | # Remember to never publicly share your keystore.
10 | # See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app
11 | key.properties
12 | **/*.keystore
13 | **/*.jks
14 |
--------------------------------------------------------------------------------
/android/app/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id "com.android.application"
3 | id "kotlin-android"
4 | id "dev.flutter.flutter-gradle-plugin"
5 | }
6 |
7 | def localProperties = new Properties()
8 | def localPropertiesFile = rootProject.file('local.properties')
9 | if (localPropertiesFile.exists()) {
10 | localPropertiesFile.withReader('UTF-8') { reader ->
11 | localProperties.load(reader)
12 | }
13 | }
14 |
15 | def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
16 | if (flutterVersionCode == null) {
17 | flutterVersionCode = '1'
18 | }
19 |
20 | def flutterVersionName = localProperties.getProperty('flutter.versionName')
21 | if (flutterVersionName == null) {
22 | flutterVersionName = '1.0'
23 | }
24 |
25 | android {
26 | namespace "com.example.flutter_ui_examples"
27 | compileSdkVersion flutter.compileSdkVersion
28 | ndkVersion flutter.ndkVersion
29 |
30 | compileOptions {
31 | sourceCompatibility JavaVersion.VERSION_1_8
32 | targetCompatibility JavaVersion.VERSION_1_8
33 | }
34 |
35 | kotlinOptions {
36 | jvmTarget = '1.8'
37 | }
38 |
39 | sourceSets {
40 | main.java.srcDirs += 'src/main/kotlin'
41 | }
42 |
43 | defaultConfig {
44 | // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
45 | applicationId "com.example.flutter_ui_examples"
46 | // You can update the following values to match your application needs.
47 | // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration.
48 | minSdkVersion flutter.minSdkVersion
49 | targetSdkVersion flutter.targetSdkVersion
50 | versionCode flutterVersionCode.toInteger()
51 | versionName flutterVersionName
52 | }
53 |
54 | buildTypes {
55 | release {
56 | // TODO: Add your own signing config for the release build.
57 | // Signing with the debug keys for now, so `flutter run --release` works.
58 | signingConfig signingConfigs.debug
59 | }
60 | }
61 | }
62 |
63 | flutter {
64 | source '../..'
65 | }
66 |
67 | dependencies {}
68 |
--------------------------------------------------------------------------------
/android/app/src/debug/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/android/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
8 |
16 |
20 |
24 |
25 |
26 |
27 |
28 |
29 |
31 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/android/app/src/main/kotlin/com/example/flutter_ui_examples/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.example.flutter_ui_examples
2 |
3 | import io.flutter.embedding.android.FlutterActivity
4 |
5 | class MainActivity: FlutterActivity() {
6 | }
7 |
--------------------------------------------------------------------------------
/android/app/src/main/res/drawable-v21/launch_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
12 |
13 |
--------------------------------------------------------------------------------
/android/app/src/main/res/drawable/launch_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
12 |
13 |
--------------------------------------------------------------------------------
/android/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/android/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/android/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/android/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/android/app/src/main/res/values-night/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
9 |
15 |
18 |
19 |
--------------------------------------------------------------------------------
/android/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
9 |
15 |
18 |
19 |
--------------------------------------------------------------------------------
/android/app/src/profile/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/android/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | ext.kotlin_version = '1.7.10'
3 | repositories {
4 | google()
5 | mavenCentral()
6 | }
7 |
8 | dependencies {
9 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
10 | }
11 | }
12 |
13 | allprojects {
14 | repositories {
15 | google()
16 | mavenCentral()
17 | }
18 | }
19 |
20 | rootProject.buildDir = '../build'
21 | subprojects {
22 | project.buildDir = "${rootProject.buildDir}/${project.name}"
23 | }
24 | subprojects {
25 | project.evaluationDependsOn(':app')
26 | }
27 |
28 | tasks.register("clean", Delete) {
29 | delete rootProject.buildDir
30 | }
31 |
--------------------------------------------------------------------------------
/android/gradle.properties:
--------------------------------------------------------------------------------
1 | org.gradle.jvmargs=-Xmx4G
2 | android.useAndroidX=true
3 | android.enableJetifier=true
4 |
--------------------------------------------------------------------------------
/android/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | zipStoreBase=GRADLE_USER_HOME
4 | zipStorePath=wrapper/dists
5 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-all.zip
6 |
--------------------------------------------------------------------------------
/android/settings.gradle:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | def flutterSdkPath = {
3 | def properties = new Properties()
4 | file("local.properties").withInputStream { properties.load(it) }
5 | def flutterSdkPath = properties.getProperty("flutter.sdk")
6 | assert flutterSdkPath != null, "flutter.sdk not set in local.properties"
7 | return flutterSdkPath
8 | }
9 | settings.ext.flutterSdkPath = flutterSdkPath()
10 |
11 | includeBuild("${settings.ext.flutterSdkPath}/packages/flutter_tools/gradle")
12 |
13 | repositories {
14 | google()
15 | mavenCentral()
16 | gradlePluginPortal()
17 | }
18 |
19 | plugins {
20 | id "dev.flutter.flutter-gradle-plugin" version "1.0.0" apply false
21 | }
22 | }
23 |
24 | plugins {
25 | id "dev.flutter.flutter-plugin-loader" version "1.0.0"
26 | id "com.android.application" version "7.3.0" apply false
27 | }
28 |
29 | include ":app"
30 |
--------------------------------------------------------------------------------
/assets/6392956.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/assets/6392956.jpg
--------------------------------------------------------------------------------
/calculate.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Directory containing the files
4 | BUILD_DIR="build"
5 |
6 | # File patterns to match
7 | PATTERNS=(
8 | "scrolling_timeline_global_keys_*.timeline_summary.json"
9 | "scrolling_timeline_no_keys_*.timeline_summary.json"
10 | "scrolling_timeline_value_keys_*.timeline_summary.json"
11 | "scrolling_timeline_slivers_prototype_*.timeline_summary.json"
12 | "scrolling_timeline_sliver_*.timeline_summary.json"
13 | "scrolling_timeline_shrink_wrap_*.timeline_summary.json"
14 | "scrolling_timeline_shrink_wrap_never_scrollable_*.timeline_summary.json"
15 | )
16 |
17 | # Function to calculate the average of a given field for a given pattern
18 | calculate_average() {
19 | local pattern=$1
20 | local field=$2
21 | local total_value=0
22 | local file_count=0
23 |
24 | # Iterate over matching files
25 | for file in "$BUILD_DIR"/$pattern; do
26 | # Check if file exists
27 | if [[ -f "$file" ]]; then
28 | # Extract the value of the given field from the JSON file
29 | value=$(jq ".$field" "$file")
30 |
31 | # Add the value to the total
32 | total_value=$(echo "$total_value + $value" | bc)
33 |
34 | # Increment the file count
35 | ((file_count++))
36 | fi
37 | done
38 |
39 | # Calculate the average value
40 | if [[ $file_count -gt 0 ]]; then
41 | average_value=$(echo "scale=2; $total_value / $file_count" | bc)
42 | echo "$pattern: Average $field: $average_value"
43 | else
44 | echo "$pattern: No matching files found."
45 | fi
46 | }
47 |
48 | # Main script
49 | if [[ $# -lt 1 ]]; then
50 | echo "Usage: $0 field_name [field_name ...]"
51 | exit 1
52 | fi
53 |
54 | # Iterate over each field provided as argument
55 | for field in "$@"; do
56 | echo "Calculating averages for field: $field"
57 | for pattern in "${PATTERNS[@]}"; do
58 | calculate_average "$pattern" "$field"
59 | done
60 | echo
61 | done
62 |
--------------------------------------------------------------------------------
/i18n/.gitignore:
--------------------------------------------------------------------------------
1 | # Miscellaneous
2 | *.class
3 | *.log
4 | *.pyc
5 | *.swp
6 | .DS_Store
7 | .atom/
8 | .buildlog/
9 | .history
10 | .svn/
11 |
12 | # IntelliJ related
13 | *.iml
14 | *.ipr
15 | *.iws
16 | .idea/
17 |
18 | # The .vscode folder contains launch configuration and tasks you configure in
19 | # VS Code which you may wish to be included in version control, so this line
20 | # is commented out by default.
21 | #.vscode/
22 |
23 | # Flutter/Dart/Pub related
24 | # Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock.
25 | /pubspec.lock
26 | **/doc/api/
27 | .dart_tool/
28 | .packages
29 | build/
30 |
--------------------------------------------------------------------------------
/i18n/.metadata:
--------------------------------------------------------------------------------
1 | # This file tracks properties of this Flutter project.
2 | # Used by Flutter tool to assess capabilities and perform upgrades etc.
3 | #
4 | # This file should be version controlled and should not be manually edited.
5 |
6 | version:
7 | revision: 7e9793dee1b85a243edd0e06cb1658e98b077561
8 | channel: stable
9 |
10 | project_type: package
11 |
--------------------------------------------------------------------------------
/i18n/lib/i18n.dart:
--------------------------------------------------------------------------------
1 | library i18n;
2 |
3 | export 'strings.g.dart';
4 |
--------------------------------------------------------------------------------
/i18n/lib/strings.i18n.json:
--------------------------------------------------------------------------------
1 | {
2 | "tasksDone": {
3 | "one": "You have done $completed of $n tasks",
4 | "other": "You have done $completed of $n tasks"
5 | },
6 | "tasksDoneShort": {
7 | "one": "$completed/$n tasks done",
8 | "other": "$completed/$n tasks done"
9 | },
10 | "agreeWithTerms": "I have read and agree with terms and conditions, privacy policy",
11 | "usersOnline": {
12 | "one": "$n user online",
13 | "other": "$n users online"
14 | }
15 |
16 | }
--------------------------------------------------------------------------------
/i18n/lib/strings_de.i18n.json:
--------------------------------------------------------------------------------
1 | {
2 | "tasksDone": {
3 | "one": "You have done $completed of $n tasks",
4 | "other": "You have done $completed of $n tasks"
5 | },
6 | "tasksDoneShort": {
7 | "one": "$completed/$n tasks done",
8 | "other": "$completed/$n tasks done"
9 | },
10 | "agreeWithTerms": "Ich habe die Bedingungen und Datenschutzrichtlinie gelesen und akzeptiere sie",
11 | "usersOnline": {
12 | "one": "$n user online",
13 | "other": "$n users online"
14 | }
15 | }
--------------------------------------------------------------------------------
/i18n/lib/strings_ru.i18n.json:
--------------------------------------------------------------------------------
1 | {
2 | "tasksDone": {
3 | "one": "You have done $completed of $n tasks",
4 | "other": "You have done $completed of $n tasks"
5 | },
6 | "tasksDoneShort": {
7 | "one": "$completed/$n tasks done",
8 | "other": "$completed/$n tasks done"
9 | },
10 | "agreeWithTerms": "Ich habe die Bedingungen und Datenschutzrichtlinie gelesen und akzeptiere sie",
11 | "usersOnline": {
12 | "one": "$n пользователь онлайн",
13 | "few": "$n пользователя онлайн",
14 | "many": "$n пользователей онлайн",
15 | "other": "$n пользователя онлайн"
16 | }
17 | }
--------------------------------------------------------------------------------
/i18n/pubspec.yaml:
--------------------------------------------------------------------------------
1 | name: i18n
2 | description: i18n
3 | version: 0.0.1
4 | publish_to: none
5 |
6 | environment:
7 | sdk: ">=2.19.0 <3.0.0"
8 | flutter: ">=3.7.0"
9 |
10 | dependencies:
11 | flutter:
12 | sdk: flutter
13 |
14 | dev_dependencies:
15 | flutter_test:
16 | sdk: flutter
17 | flutter_lints: ^2.0.1
18 |
19 | flutter:
20 |
--------------------------------------------------------------------------------
/integration_test/elements_test.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 | import 'package:flutter/widgets.dart';
3 | import 'package:flutter_test/flutter_test.dart';
4 | import 'package:flutter_ui_examples/main.dart';
5 |
6 | void main() {
7 | testWidgets('Check elements', (tester) async {
8 | await tester.pumpWidget(Container(
9 | color: Colors.red,
10 | ));
11 | tester.allElements;
12 | tester.allRenderObjects;
13 | tester.allWidgets;
14 | tester.allStates;
15 | tester.layers;
16 |
17 | });
18 | }
--------------------------------------------------------------------------------
/integration_test/keyed_list_view_scrolling_test.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 | import 'package:flutter_test/flutter_test.dart';
3 | import 'package:flutter_ui_examples/3_list_view_mistakes/list_view_keys.dart';
4 | import 'package:flutter_ui_examples/main.dart';
5 | import 'package:integration_test/integration_test.dart';
6 |
7 | void main() {
8 | final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
9 |
10 | Future _test(
11 | WidgetTester tester, Widget child, String reportKey) async {
12 | // Build our app and trigger a frame.
13 | await tester.pumpWidget(MyApp(child: child));
14 |
15 | final listFinder = find.byType(Scrollable);
16 | final itemFinder = find.byKey(const ValueKey('last_item'));
17 |
18 | await binding.traceAction(
19 | () async {
20 | // Scroll until the item to be found appears.
21 | await tester.scrollUntilVisible(
22 | itemFinder,
23 | 150.0,
24 | scrollable: listFinder,
25 | maxScrolls: 1000,
26 | );
27 | },
28 | retainPriorEvents: true,
29 | reportKey: reportKey,
30 | );
31 | }
32 |
33 | testWidgets('Scrolling test no keys', (tester) async {
34 | await _test(tester, ListViewKeys.noKeys(), 'scrolling_timeline_no_keys');
35 | });
36 |
37 | testWidgets('Scrolling test global keys', (tester) async {
38 | await _test(
39 | tester, ListViewKeys.globalKeys(), 'scrolling_timeline_global_keys');
40 | });
41 |
42 | testWidgets('Scrolling test value keys', (tester) async {
43 | await _test(
44 | tester, ListViewKeys.valueKeys(), 'scrolling_timeline_value_keys');
45 | });
46 | }
47 |
--------------------------------------------------------------------------------
/integration_test/prototyped_list_view_scrolling_test.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 | import 'package:flutter/widgets.dart';
3 | import 'package:flutter_driver/flutter_driver.dart' as driver;
4 | import 'package:flutter_test/flutter_test.dart';
5 | import 'package:flutter_ui_examples/3_list_view_mistakes/list_view_keys.dart';
6 | import 'package:flutter_ui_examples/3_list_view_mistakes/list_view_never_scrollable_slivers.dart';
7 | import 'package:flutter_ui_examples/main.dart';
8 | import 'package:integration_test/integration_test.dart';
9 |
10 | void main() {
11 | final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
12 |
13 |
14 | final shrinkWrap = Scaffold(
15 | body: SafeArea(
16 | child: ListView.builder(
17 | key: Key('scrollable'),
18 | itemCount: 1000,
19 | shrinkWrap: true,
20 | itemBuilder: (context, index) {
21 | return Card(
22 | key: index == 999 ? ValueKey("last_item") : null,
23 | child: Text(index.toString()));
24 | },
25 | ),
26 | ),
27 | );
28 |
29 | final shrinkWrapAndNeverScrollable = Scaffold(
30 | body: SafeArea(
31 | child: ListView(
32 | key: Key('scrollable'),
33 | primary: true,
34 | children: [
35 | ListView.builder(
36 | itemCount: 1000,
37 | physics: NeverScrollableScrollPhysics(),
38 | shrinkWrap: true,
39 | itemBuilder: (context, index) {
40 | // print("building item #${index}");
41 | return Card(
42 | key: index == 999 ? ValueKey("last_item") : null,
43 | child: Text(index.toString()));
44 | },
45 | ),
46 | ],
47 | ),
48 | ),
49 | );
50 |
51 | final slivers = Scaffold(
52 | body: SafeArea(
53 | child: CustomScrollView(
54 | key: const Key('scrollable'),
55 | slivers: [
56 | const SliverToBoxAdapter(child: Card(child: Text("Header card"))),
57 | SliverList.builder(
58 | itemCount: 1000,
59 | itemBuilder: (context, index) {
60 | // print("building item #${index}");
61 | return Card(child: Text(index.toString()));
62 | },
63 | ),
64 | const SliverToBoxAdapter(
65 | child: Card(
66 | key: ValueKey('last_item'), child: Text("Footer card"))),
67 | ],
68 | ),
69 | ),
70 | );
71 |
72 | final sliversPrototype = ListViewNeverScrollableSlivers();
73 |
74 |
75 | Future _test(
76 | WidgetTester tester, Widget child, String reportKey) async {
77 | // Build our app and trigger a frame.
78 | await tester.pumpWidget(MyApp(child: child));
79 | await tester.pumpAndSettle();
80 |
81 | await binding.traceAction(
82 | () async {
83 | // Scroll until the item to be found appears.
84 | await tester.scrollUntilVisible(
85 | find.byKey(ValueKey('last_item')),
86 | 150.0,
87 | scrollable: find.byType(Scrollable).at(0),
88 | maxScrolls: 1000,
89 | );
90 | await tester.pump();
91 | },
92 | retainPriorEvents: true,
93 | reportKey: reportKey,
94 | );
95 | await Future.delayed(const Duration(seconds: 1));
96 | }
97 |
98 | testWidgets('Scrolling with Slivers', (tester) async {
99 | await _test(tester, shrinkWrapAndNeverScrollable, 'scrolling_timeline_shrink_wrap_never_scrollable');
100 | await _test(tester, shrinkWrap, 'scrolling_timeline_shrink_wrap');
101 | await _test(tester, slivers, 'scrolling_timeline_sliver');
102 | await _test(tester, sliversPrototype, 'scrolling_timeline_slivers_prototype');
103 | });
104 | }
105 |
--------------------------------------------------------------------------------
/ios/.gitignore:
--------------------------------------------------------------------------------
1 | **/dgph
2 | *.mode1v3
3 | *.mode2v3
4 | *.moved-aside
5 | *.pbxuser
6 | *.perspectivev3
7 | **/*sync/
8 | .sconsign.dblite
9 | .tags*
10 | **/.vagrant/
11 | **/DerivedData/
12 | Icon?
13 | **/Pods/
14 | **/.symlinks/
15 | profile
16 | xcuserdata
17 | **/.generated/
18 | Flutter/App.framework
19 | Flutter/Flutter.framework
20 | Flutter/Flutter.podspec
21 | Flutter/Generated.xcconfig
22 | Flutter/ephemeral/
23 | Flutter/app.flx
24 | Flutter/app.zip
25 | Flutter/flutter_assets/
26 | Flutter/flutter_export_environment.sh
27 | ServiceDefinitions.json
28 | Runner/GeneratedPluginRegistrant.*
29 |
30 | # Exceptions to above rules.
31 | !default.mode1v3
32 | !default.mode2v3
33 | !default.pbxuser
34 | !default.perspectivev3
35 |
--------------------------------------------------------------------------------
/ios/Flutter/AppFrameworkInfo.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleExecutable
8 | App
9 | CFBundleIdentifier
10 | io.flutter.flutter.app
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundleName
14 | App
15 | CFBundlePackageType
16 | FMWK
17 | CFBundleShortVersionString
18 | 1.0
19 | CFBundleSignature
20 | ????
21 | CFBundleVersion
22 | 1.0
23 | MinimumOSVersion
24 | 12.0
25 |
26 |
27 |
--------------------------------------------------------------------------------
/ios/Flutter/Debug.xcconfig:
--------------------------------------------------------------------------------
1 | #include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"
2 | #include "Generated.xcconfig"
3 |
--------------------------------------------------------------------------------
/ios/Flutter/Release.xcconfig:
--------------------------------------------------------------------------------
1 | #include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"
2 | #include "Generated.xcconfig"
3 |
--------------------------------------------------------------------------------
/ios/Podfile:
--------------------------------------------------------------------------------
1 | # Uncomment this line to define a global platform for your project
2 | # platform :ios, '12.0'
3 |
4 | # CocoaPods analytics sends network stats synchronously affecting flutter build latency.
5 | ENV['COCOAPODS_DISABLE_STATS'] = 'true'
6 |
7 | project 'Runner', {
8 | 'Debug' => :debug,
9 | 'Profile' => :release,
10 | 'Release' => :release,
11 | }
12 |
13 | def flutter_root
14 | generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
15 | unless File.exist?(generated_xcode_build_settings_path)
16 | raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
17 | end
18 |
19 | File.foreach(generated_xcode_build_settings_path) do |line|
20 | matches = line.match(/FLUTTER_ROOT\=(.*)/)
21 | return matches[1].strip if matches
22 | end
23 | raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
24 | end
25 |
26 | require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)
27 |
28 | flutter_ios_podfile_setup
29 |
30 | target 'Runner' do
31 | use_frameworks!
32 | use_modular_headers!
33 |
34 | flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
35 | target 'RunnerTests' do
36 | inherit! :search_paths
37 | end
38 | end
39 |
40 | post_install do |installer|
41 | installer.pods_project.targets.each do |target|
42 | flutter_additional_ios_build_settings(target)
43 | end
44 | end
45 |
--------------------------------------------------------------------------------
/ios/Podfile.lock:
--------------------------------------------------------------------------------
1 | PODS:
2 | - Flutter (1.0.0)
3 | - integration_test (0.0.1):
4 | - Flutter
5 | - path_provider_foundation (0.0.1):
6 | - Flutter
7 | - FlutterMacOS
8 |
9 | DEPENDENCIES:
10 | - Flutter (from `Flutter`)
11 | - integration_test (from `.symlinks/plugins/integration_test/ios`)
12 | - path_provider_foundation (from `.symlinks/plugins/path_provider_foundation/darwin`)
13 |
14 | EXTERNAL SOURCES:
15 | Flutter:
16 | :path: Flutter
17 | integration_test:
18 | :path: ".symlinks/plugins/integration_test/ios"
19 | path_provider_foundation:
20 | :path: ".symlinks/plugins/path_provider_foundation/darwin"
21 |
22 | SPEC CHECKSUMS:
23 | Flutter: e0871f40cf51350855a761d2e70bf5af5b9b5de7
24 | integration_test: 252f60fa39af5e17c3aa9899d35d908a0721b573
25 | path_provider_foundation: 2b6b4c569c0fb62ec74538f866245ac84301af46
26 |
27 | PODFILE CHECKSUM: 819463e6a0290f5a72f145ba7cde16e8b6ef0796
28 |
29 | COCOAPODS: 1.15.2
30 |
--------------------------------------------------------------------------------
/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | PreviewsEnabled
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme:
--------------------------------------------------------------------------------
1 |
2 |
5 |
8 |
9 |
15 |
21 |
22 |
23 |
24 |
25 |
30 |
31 |
37 |
38 |
39 |
40 |
43 |
49 |
50 |
51 |
52 |
53 |
63 |
65 |
71 |
72 |
73 |
74 |
80 |
82 |
88 |
89 |
90 |
91 |
93 |
94 |
97 |
98 |
99 |
--------------------------------------------------------------------------------
/ios/Runner.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | PreviewsEnabled
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/ios/Runner/AppDelegate.swift:
--------------------------------------------------------------------------------
1 | import UIKit
2 | import Flutter
3 |
4 | @main
5 | @objc class AppDelegate: FlutterAppDelegate {
6 | override func application(
7 | _ application: UIApplication,
8 | didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
9 | ) -> Bool {
10 | GeneratedPluginRegistrant.register(with: self)
11 | return super.application(application, didFinishLaunchingWithOptions: launchOptions)
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "size" : "20x20",
5 | "idiom" : "iphone",
6 | "filename" : "Icon-App-20x20@2x.png",
7 | "scale" : "2x"
8 | },
9 | {
10 | "size" : "20x20",
11 | "idiom" : "iphone",
12 | "filename" : "Icon-App-20x20@3x.png",
13 | "scale" : "3x"
14 | },
15 | {
16 | "size" : "29x29",
17 | "idiom" : "iphone",
18 | "filename" : "Icon-App-29x29@1x.png",
19 | "scale" : "1x"
20 | },
21 | {
22 | "size" : "29x29",
23 | "idiom" : "iphone",
24 | "filename" : "Icon-App-29x29@2x.png",
25 | "scale" : "2x"
26 | },
27 | {
28 | "size" : "29x29",
29 | "idiom" : "iphone",
30 | "filename" : "Icon-App-29x29@3x.png",
31 | "scale" : "3x"
32 | },
33 | {
34 | "size" : "40x40",
35 | "idiom" : "iphone",
36 | "filename" : "Icon-App-40x40@2x.png",
37 | "scale" : "2x"
38 | },
39 | {
40 | "size" : "40x40",
41 | "idiom" : "iphone",
42 | "filename" : "Icon-App-40x40@3x.png",
43 | "scale" : "3x"
44 | },
45 | {
46 | "size" : "60x60",
47 | "idiom" : "iphone",
48 | "filename" : "Icon-App-60x60@2x.png",
49 | "scale" : "2x"
50 | },
51 | {
52 | "size" : "60x60",
53 | "idiom" : "iphone",
54 | "filename" : "Icon-App-60x60@3x.png",
55 | "scale" : "3x"
56 | },
57 | {
58 | "size" : "20x20",
59 | "idiom" : "ipad",
60 | "filename" : "Icon-App-20x20@1x.png",
61 | "scale" : "1x"
62 | },
63 | {
64 | "size" : "20x20",
65 | "idiom" : "ipad",
66 | "filename" : "Icon-App-20x20@2x.png",
67 | "scale" : "2x"
68 | },
69 | {
70 | "size" : "29x29",
71 | "idiom" : "ipad",
72 | "filename" : "Icon-App-29x29@1x.png",
73 | "scale" : "1x"
74 | },
75 | {
76 | "size" : "29x29",
77 | "idiom" : "ipad",
78 | "filename" : "Icon-App-29x29@2x.png",
79 | "scale" : "2x"
80 | },
81 | {
82 | "size" : "40x40",
83 | "idiom" : "ipad",
84 | "filename" : "Icon-App-40x40@1x.png",
85 | "scale" : "1x"
86 | },
87 | {
88 | "size" : "40x40",
89 | "idiom" : "ipad",
90 | "filename" : "Icon-App-40x40@2x.png",
91 | "scale" : "2x"
92 | },
93 | {
94 | "size" : "76x76",
95 | "idiom" : "ipad",
96 | "filename" : "Icon-App-76x76@1x.png",
97 | "scale" : "1x"
98 | },
99 | {
100 | "size" : "76x76",
101 | "idiom" : "ipad",
102 | "filename" : "Icon-App-76x76@2x.png",
103 | "scale" : "2x"
104 | },
105 | {
106 | "size" : "83.5x83.5",
107 | "idiom" : "ipad",
108 | "filename" : "Icon-App-83.5x83.5@2x.png",
109 | "scale" : "2x"
110 | },
111 | {
112 | "size" : "1024x1024",
113 | "idiom" : "ios-marketing",
114 | "filename" : "Icon-App-1024x1024@1x.png",
115 | "scale" : "1x"
116 | }
117 | ],
118 | "info" : {
119 | "version" : 1,
120 | "author" : "xcode"
121 | }
122 | }
123 |
--------------------------------------------------------------------------------
/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png
--------------------------------------------------------------------------------
/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png
--------------------------------------------------------------------------------
/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png
--------------------------------------------------------------------------------
/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png
--------------------------------------------------------------------------------
/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png
--------------------------------------------------------------------------------
/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png
--------------------------------------------------------------------------------
/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png
--------------------------------------------------------------------------------
/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png
--------------------------------------------------------------------------------
/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png
--------------------------------------------------------------------------------
/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png
--------------------------------------------------------------------------------
/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png
--------------------------------------------------------------------------------
/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png
--------------------------------------------------------------------------------
/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png
--------------------------------------------------------------------------------
/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png
--------------------------------------------------------------------------------
/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png
--------------------------------------------------------------------------------
/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "universal",
5 | "filename" : "LaunchImage.png",
6 | "scale" : "1x"
7 | },
8 | {
9 | "idiom" : "universal",
10 | "filename" : "LaunchImage@2x.png",
11 | "scale" : "2x"
12 | },
13 | {
14 | "idiom" : "universal",
15 | "filename" : "LaunchImage@3x.png",
16 | "scale" : "3x"
17 | }
18 | ],
19 | "info" : {
20 | "version" : 1,
21 | "author" : "xcode"
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png
--------------------------------------------------------------------------------
/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png
--------------------------------------------------------------------------------
/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png
--------------------------------------------------------------------------------
/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md:
--------------------------------------------------------------------------------
1 | # Launch Screen Assets
2 |
3 | You can customize the launch screen with your own desired assets by replacing the image files in this directory.
4 |
5 | You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images.
--------------------------------------------------------------------------------
/ios/Runner/Base.lproj/LaunchScreen.storyboard:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/ios/Runner/Base.lproj/Main.storyboard:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/ios/Runner/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleLocalizations
6 |
7 | en
8 | et
9 | de
10 |
11 | CFBundleDevelopmentRegion
12 | $(DEVELOPMENT_LANGUAGE)
13 | CFBundleDisplayName
14 | Flutter Ui Examples
15 | CFBundleExecutable
16 | $(EXECUTABLE_NAME)
17 | CFBundleIdentifier
18 | $(PRODUCT_BUNDLE_IDENTIFIER)
19 | CFBundleInfoDictionaryVersion
20 | 6.0
21 | CFBundleName
22 | flutter_ui_examples
23 | CFBundlePackageType
24 | APPL
25 | CFBundleShortVersionString
26 | $(FLUTTER_BUILD_NAME)
27 | CFBundleSignature
28 | ????
29 | CFBundleVersion
30 | $(FLUTTER_BUILD_NUMBER)
31 | LSRequiresIPhoneOS
32 |
33 | UILaunchStoryboardName
34 | LaunchScreen
35 | UIMainStoryboardFile
36 | Main
37 | UISupportedInterfaceOrientations
38 |
39 | UIInterfaceOrientationPortrait
40 | UIInterfaceOrientationLandscapeLeft
41 | UIInterfaceOrientationLandscapeRight
42 |
43 | UISupportedInterfaceOrientations~ipad
44 |
45 | UIInterfaceOrientationPortrait
46 | UIInterfaceOrientationPortraitUpsideDown
47 | UIInterfaceOrientationLandscapeLeft
48 | UIInterfaceOrientationLandscapeRight
49 |
50 | CADisableMinimumFrameDurationOnPhone
51 |
52 | UIApplicationSupportsIndirectInputEvents
53 |
54 |
55 |
56 |
--------------------------------------------------------------------------------
/ios/Runner/Runner-Bridging-Header.h:
--------------------------------------------------------------------------------
1 | #import "GeneratedPluginRegistrant.h"
2 |
--------------------------------------------------------------------------------
/ios/RunnerTests/RunnerTests.swift:
--------------------------------------------------------------------------------
1 | import Flutter
2 | import UIKit
3 | import XCTest
4 |
5 | class RunnerTests: XCTestCase {
6 |
7 | func testExample() {
8 | // If you add code to the Runner application, consider adding tests here.
9 | // See https://developer.apple.com/documentation/xctest for more information about using XCTest.
10 | }
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/lib/10_media_query/media_query_example.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 |
3 | class MediaQueryExample extends StatelessWidget {
4 | const MediaQueryExample({super.key});
5 |
6 | @override
7 | Widget build(BuildContext context) {
8 | print("----");
9 | print("size: ${MediaQuery.sizeOf(context)}");
10 | print("viewInsets: ${MediaQuery.viewInsetsOf(context)}");
11 | print("viewPadding: ${MediaQuery.viewPaddingOf(context)}");
12 | print("padding: ${MediaQuery.paddingOf(context)}");
13 |
14 | final element = context.getElementForInheritedWidgetOfExactType();
15 |
16 | DefaultTextStyle.of(context);
17 | final defaultTextStyleElement = context.getElementForInheritedWidgetOfExactType();
18 | // MediaQuery.displayFeaturesOf(context); android only
19 | return Scaffold(
20 |
21 | );
22 | }
23 | }
--------------------------------------------------------------------------------
/lib/11_deferred_indexed_stack/deferred_indexed_stack_example.dart:
--------------------------------------------------------------------------------
1 | import 'package:deferred_indexed_stack/deferred_indexed_stack.dart';
2 | import 'package:flutter/material.dart';
3 |
4 | class DeferredIndexedStackExample extends StatefulWidget {
5 | const DeferredIndexedStackExample({super.key});
6 |
7 | @override
8 | State createState() => _DeferredIndexedStackExampleState();
9 | }
10 |
11 | class _DeferredIndexedStackExampleState extends State {
12 | final _controller = DeferredIndexedStackController();
13 |
14 | @override
15 | void initState() {
16 | // TODO: implement initState
17 | super.initState();
18 | _controller.initChildAt(1);
19 | }
20 |
21 | @override
22 | Widget build(BuildContext context) {
23 | return SizedBox();
24 | // return Scaffold(
25 | // body: DeferredIndexedStack(
26 | // controller: _controller,
27 | // children: [
28 | // DeferredTab(child: TabA()),
29 | // DeferredTab(
30 | // id: tabB,
31 | // child: TabB(),
32 | // ),
33 | // DeferredTab(
34 | // id: tabC,
35 | // child: TabC(),
36 | // ),
37 | // DeferredTab(
38 | // id: tabD,
39 | // deferredFor: Duration(seconds: 5),
40 | // child: TabD(),
41 | // ),
42 | // ])
43 | // );
44 | }
45 | }
--------------------------------------------------------------------------------
/lib/12_gestures/custom_button.dart:
--------------------------------------------------------------------------------
1 | import 'dart:math';
2 |
3 | import 'package:flutter/gestures.dart';
4 | import 'package:flutter/material.dart';
5 |
6 | class CustomGestureButton extends StatefulWidget {
7 | final GestureTapCallback onTap;
8 |
9 | const CustomGestureButton({super.key, required this.onTap});
10 |
11 | @override
12 | State createState() => _CustomGestureButton();
13 | }
14 |
15 | class _CustomGestureButton extends State {
16 | Offset _panUpdatePosition = Offset.zero;
17 | bool _isPressed = false;
18 |
19 | @override
20 | Widget build(BuildContext context) {
21 | final color = Color.lerp(
22 | Colors.blue,
23 | Color.fromARGB(255, 33, 76, 176),
24 | (_isPressed ? 0.5 : 0.0) +
25 | 0.5 * (min(400, _panUpdatePosition.distance) / 400),
26 | );
27 | return DecoratedBox(
28 | decoration: BoxDecoration(
29 | color: color,
30 | borderRadius: BorderRadius.circular(20),
31 | ),
32 | child: GestureDetector(
33 | behavior: HitTestBehavior.opaque,
34 | onTap: () {
35 | print('onTap');
36 | },
37 | onPanDown: (details) {
38 | setState(() {
39 | _isPressed = true;
40 | });
41 | },
42 | onPanUpdate: (details) {
43 | setState(() {
44 | _panUpdatePosition = _panUpdatePosition - details.delta;
45 | });
46 | },
47 | onPanEnd: (details) {
48 | setState(() {
49 | _panUpdatePosition = Offset.zero;
50 | _isPressed = false;
51 | });
52 | },
53 | onPanCancel: () {
54 | setState(() {
55 | _panUpdatePosition = Offset.zero;
56 | _isPressed = false;
57 | });
58 | },
59 | child: Padding(
60 | padding: const EdgeInsets.symmetric(horizontal: 40, vertical: 20),
61 | child: Transform.scale(
62 | scale: 1 - min(400, _panUpdatePosition.distance) / 1500,
63 | child: Transform.translate(
64 | offset: Offset(
65 | translateDistance(_panUpdatePosition.dx / 10, 40),
66 | translateDistance(_panUpdatePosition.dy / 10, 20),
67 | ),
68 | child: Text(
69 | "Button",
70 | style: TextStyle(
71 | fontSize: 22,
72 | color: Colors.white.withOpacity(
73 | 1 - min(400, _panUpdatePosition.distance) / 400),
74 | ),
75 | ),
76 | ),
77 | ),
78 | ),
79 | ),
80 | );
81 | }
82 |
83 | double translateDistance(double distance, double limit) {
84 | return limit * sin(distance.clamp(-limit, limit) / limit);
85 | }
86 | }
--------------------------------------------------------------------------------
/lib/12_gestures/custom_scale_detector.dart:
--------------------------------------------------------------------------------
1 | import 'dart:math';
2 |
3 | import 'package:flutter/material.dart';
4 |
5 | class CustomScaleDetector extends StatefulWidget {
6 | const CustomScaleDetector({super.key});
7 |
8 | @override
9 | State createState() => _CustomScaleDetectorState();
10 | }
11 |
12 | class _CustomScaleDetectorState extends State {
13 | double scaleOnStart = 1.0;
14 | double scale = 1.0;
15 | double scaleDelta = 0.0;
16 | Offset? localFocalPoint;
17 |
18 | @override
19 | Widget build(BuildContext context) {
20 | return GestureDetector(
21 | onScaleStart: (details) {
22 | scaleOnStart = scale;
23 | },
24 | onScaleUpdate: (details) {
25 | if (details.pointerCount == 1) {
26 | return;
27 | }
28 | setState(() {
29 | scaleDelta = scale - details.scale;
30 |
31 | // if (details.pointerCount > 1) {
32 | scale = scaleOnStart * details.scale;
33 |
34 | // }
35 | // if (details.pointerCount > 1) {
36 | localFocalPoint = details.localFocalPoint;
37 | // }
38 | });
39 | },
40 | onScaleEnd: (details) {},
41 | child: CustomPaint(
42 | painter:
43 | CustomScalePainter(scale: scale, localFocalPoint: localFocalPoint, scaleDelta: scaleDelta),
44 | child: Container(
45 | decoration: BoxDecoration(
46 | border: Border.all(color: Colors.black, width: 2),
47 | ),
48 | width: 300,
49 | height: 300,
50 | ),
51 | ),
52 | );
53 | }
54 | }
55 |
56 | class CustomScalePainter extends CustomPainter {
57 | final double scale;
58 | final double scaleDelta;
59 | Offset? localFocalPoint;
60 | Offset? blackCircleCenter;
61 |
62 | CustomScalePainter(
63 | {super.repaint, required this.scale, required this.scaleDelta, required this.localFocalPoint});
64 |
65 | @override
66 | void paint(Canvas canvas, Size size) {
67 | final paint = Paint()
68 | ..color = Colors.blue
69 | ..strokeWidth = 5
70 | ..style = PaintingStyle.stroke;
71 |
72 |
73 | blackCircleCenter =
74 | (Offset(size.width / 2, size.height / 2) + (localFocalPoint ?? Offset.zero) * (1 - scaleDelta));
75 | final radius = size.width * scale / 2;
76 |
77 | if (localFocalPoint != null) {
78 | canvas.drawCircle(localFocalPoint!, 2, paint);
79 |
80 | // final paint2 = Paint()
81 | // ..color = Colors.red
82 | // ..strokeWidth = 5
83 | // ..style = PaintingStyle.stroke;
84 | // canvas.drawCircle(localFocalPoint!, 2.5, paint2);
85 |
86 | TextPainter tp = TextPainter();
87 | tp.textDirection = TextDirection.ltr;
88 | tp.text = TextSpan(
89 | text: 'localFocalPoint:\n$localFocalPoint\nscale: $scale',
90 | style: TextStyle(color: Colors.black, fontSize: 16));
91 | tp.layout();
92 | tp.paint(canvas, localFocalPoint! - Offset(0, 20));
93 | }
94 | if (blackCircleCenter != null) {
95 | final paint = Paint()
96 | ..color = Colors.black
97 | ..strokeWidth = 5
98 | ..style = PaintingStyle.stroke;
99 | canvas.drawCircle(blackCircleCenter!, radius, paint);
100 |
101 | // TextPainter tp = TextPainter();
102 | // tp.textDirection = TextDirection.ltr;
103 | // tp.text = TextSpan(
104 | // text: 'blackCircleCenter:\n$blackCircleCenter',
105 | // style: TextStyle(color: Colors.black, fontSize: 16));
106 | // tp.layout();
107 | // tp.paint(canvas, blackCircleCenter! - Offset(0, 20));
108 | }
109 | }
110 |
111 | @override
112 | bool shouldRepaint(covariant CustomPainter oldDelegate) {
113 | return true;
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/lib/12_gestures/custom_scale_detector_2.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 |
3 | class CustomScaleDetector2 extends StatefulWidget {
4 | const CustomScaleDetector2({super.key});
5 |
6 | @override
7 | State createState() => _CustomScaleDetector2State();
8 | }
9 |
10 | class _CustomScaleDetector2State extends State {
11 | double _baseScale = 1.0;
12 | double _currentScale = 1.0;
13 | Offset _offset = Offset.zero;
14 | Offset? _lastFocalPoint;
15 |
16 | @override
17 | Widget build(BuildContext context) {
18 | return GestureDetector(
19 | onScaleStart: (details) {
20 | _baseScale = _currentScale;
21 | _lastFocalPoint = details.localFocalPoint;
22 | },
23 | onScaleUpdate: (details) {
24 | setState(() {
25 | if (details.pointerCount > 1) {
26 | _currentScale = (_baseScale * details.scale);
27 |
28 | // Calculate the offset based on focal point movement
29 | if (_lastFocalPoint != null) {
30 | final delta = details.localFocalPoint - _lastFocalPoint!;
31 | _offset += delta / _currentScale;
32 | _lastFocalPoint = details.localFocalPoint;
33 | }
34 | }
35 | });
36 | },
37 | onScaleEnd: (details) {
38 | _lastFocalPoint = null;
39 | },
40 | child: CustomPaint(
41 | painter: _CustomScalePainter(
42 | scale: _currentScale,
43 | offset: _offset,
44 | ),
45 | child: Container(
46 | decoration: BoxDecoration(
47 | border: Border.all(color: Colors.black, width: 2),
48 | ),
49 | width: 300,
50 | height: 500,
51 | ),
52 | ),
53 | );
54 | }
55 | }
56 |
57 | class _CustomScalePainter extends CustomPainter {
58 | final double scale;
59 | final Offset offset;
60 |
61 | _CustomScalePainter({
62 | required this.scale,
63 | required this.offset,
64 | });
65 |
66 | @override
67 | void paint(Canvas canvas, Size size) {
68 | final paint = Paint()
69 | ..color = Colors.red
70 | ..strokeWidth = 2
71 | ..style = PaintingStyle.stroke;
72 |
73 | // Save the current canvas state
74 | canvas.save();
75 |
76 | // Transform the canvas based on scale and offset
77 | final center = Offset(size.width / 2, size.height / 2);
78 | canvas.translate(center.dx, center.dy);
79 | canvas.scale(scale);
80 | canvas.translate(-center.dx, -center.dy);
81 | canvas.translate(offset.dx, offset.dy);
82 |
83 | // Draw a red square
84 | final radius = size.width / 4;
85 | canvas.drawRect(
86 | Rect.fromCenter(
87 | center: center,
88 | width: radius * 2,
89 | height: radius * 2,
90 | ),
91 | paint,
92 | );
93 |
94 | // Restore the canvas state
95 | canvas.restore();
96 | }
97 |
98 | @override
99 | bool shouldRepaint(covariant _CustomScalePainter oldDelegate) {
100 | return oldDelegate.scale != scale || oldDelegate.offset != offset;
101 | }
102 | }
103 |
--------------------------------------------------------------------------------
/lib/12_gestures/custom_tap_detector.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/gestures.dart';
2 | import 'package:flutter/material.dart';
3 |
4 | class CustomSlopeTapDetector extends StatefulWidget {
5 | final double factor;
6 | final GestureTapCallback onTap;
7 | final Widget child;
8 |
9 | const CustomSlopeTapDetector(
10 | {super.key,
11 | required this.factor,
12 | required this.onTap,
13 | required this.child});
14 |
15 | @override
16 | State createState() => _CustomSlopeTapDetectorState();
17 | }
18 |
19 | class _CustomSlopeTapDetectorState extends State {
20 | Offset? _tapDownPosition;
21 | Offset? _panUpdatePosition;
22 |
23 | @override
24 | Widget build(BuildContext context) {
25 | final touchSlope = widget.factor *
26 | (MediaQuery.gestureSettingsOf(context).touchSlop ?? kTouchSlop);
27 |
28 | return GestureDetector(
29 | onTapDown: (details) {
30 | _tapDownPosition = details.globalPosition;
31 | },
32 | onTapUp: (details) {
33 | if (_tapDownPosition != null &&
34 | (details.globalPosition - _tapDownPosition!).distance <
35 | touchSlope) {
36 | widget.onTap();
37 | }
38 | },
39 | onPanUpdate: (details) {
40 | setState(() {
41 | _panUpdatePosition = details.localPosition;
42 | print(_panUpdatePosition);
43 | });
44 | },
45 | onPanCancel: () {
46 | setState(() {
47 | _panUpdatePosition = Offset.zero;
48 | });
49 | },
50 | onTapCancel: () => _tapDownPosition = null,
51 | child: Transform.translate(
52 | offset: (_panUpdatePosition ?? Offset.zero),
53 | child: widget.child,
54 | ),
55 | );
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/lib/12_gestures/gestures_page.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 | import 'package:flutter_ui_examples/12_gestures/custom_button.dart';
3 | import 'package:flutter_ui_examples/12_gestures/custom_tap_detector.dart';
4 | import 'transform_scale_detector.dart';
5 |
6 | class GesturesPage extends StatelessWidget {
7 | const GesturesPage({super.key});
8 |
9 | @override
10 | Widget build(BuildContext context) {
11 | return Scaffold(
12 | body: SafeArea(
13 | child: Column(
14 | children: [
15 | CustomSlopeTapDetector(
16 | onTap: () => print("Tapped"),
17 | factor: 2,
18 | child: Container(
19 | width: 100,
20 | height: 20,
21 | color: Colors.red,
22 | ),
23 | ),
24 | // PanDetector(
25 | // child: Container(
26 | // height: 300,
27 | // width: 300,
28 | // color: Colors.black12,
29 | // ),
30 | // ),
31 | CustomGestureButton(
32 | onTap: () => print("Tapped"),
33 | ),
34 | const SizedBox(height: 100),
35 | // const CustomScaleDetector(),
36 | const SizedBox(height: 20),
37 | const TransformScaleDetector(),
38 | ],
39 | ),
40 | ),
41 | );
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/lib/12_gestures/pan_detector.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 |
3 | class PanDetector extends StatelessWidget {
4 | final Widget child;
5 |
6 | const PanDetector({super.key, required this.child});
7 |
8 | @override
9 | Widget build(BuildContext context) {
10 | return GestureDetector(
11 | // onTapDown: (_) => print("onTapDown"),
12 | // onTapUp: (_) => print("onTapUp"),
13 | onPanStart: (it) => print("onPanStart (${it.globalPosition})"),
14 | onPanDown: (it) => print("onPanDown (${it.globalPosition})"),
15 | onPanUpdate: (it) => print("onPanUpdate (${it.globalPosition})"),
16 | // onVerticalDragDown: (it) => print("onVerticalDragDown (${it.globalPosition})"),
17 | // onVerticalDragStart: (details) => print("onVerticalDragStart (${details.globalPosition})"),
18 | // onVerticalDragUpdate: (details) => print("onVerticalDragUpdate (${details.globalPosition})"),
19 | onPanEnd: (details) => print("onPanEnd (${details.velocity})"),
20 | onPanCancel: () => print("onPanCancel"),
21 | // onScaleStart: (details) => print("onScaleStart (${details.localFocalPoint})"),
22 |
23 | child: child,
24 | );
25 | }
26 | }
--------------------------------------------------------------------------------
/lib/12_gestures/tap_pan_button.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 |
3 | class TapPanButton extends StatefulWidget {
4 | const TapPanButton({super.key});
5 |
6 | @override
7 | State createState() => _TapPanButtonState();
8 | }
9 |
10 | class _TapPanButtonState extends State {
11 | @override
12 | Widget build(BuildContext context) {
13 | return const Placeholder();
14 | }
15 | }
--------------------------------------------------------------------------------
/lib/12_gestures/transform_scale_detector.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 |
3 | class TransformScaleDetector extends StatefulWidget {
4 | const TransformScaleDetector({super.key});
5 |
6 | @override
7 | State createState() => _TransformScaleDetectorState();
8 | }
9 |
10 | class _TransformScaleDetectorState extends State {
11 | double scaleOnStart = 1.0;
12 | double scale = 1.0;
13 | Offset offset = Offset.zero;
14 | Offset? lastFocalPoint;
15 |
16 | @override
17 | Widget build(BuildContext context) {
18 | return GestureDetector(
19 | onScaleStart: (details) {
20 | scaleOnStart = scale;
21 | lastFocalPoint = details.localFocalPoint;
22 | },
23 | onScaleUpdate: (details) {
24 | if (details.pointerCount == 1) {
25 | return;
26 | }
27 | setState(() {
28 | scale = scaleOnStart * details.scale;
29 |
30 | // Update offset based on focal point movement
31 | if (lastFocalPoint != null) {
32 | final delta = details.localFocalPoint - lastFocalPoint!;
33 | offset += delta / scale;
34 | lastFocalPoint = details.localFocalPoint;
35 | }
36 | });
37 | },
38 | onScaleEnd: (details) {
39 | lastFocalPoint = null;
40 | },
41 | child: Container(
42 | decoration: BoxDecoration(
43 | border: Border.all(color: Colors.black, width: 2),
44 | ),
45 | width: 300,
46 | height: 300,
47 | child: Transform(
48 | transform: Matrix4.identity()
49 | ..translate(offset.dx, offset.dy)
50 | ..scale(scale),
51 | alignment: Alignment.center,
52 | child: Stack(
53 | children: [
54 | Center(
55 | child: Container(
56 | width: 100,
57 | height: 100,
58 | decoration: BoxDecoration(
59 | color: Colors.transparent,
60 | border: Border.all(color: Colors.red, width: 2),
61 | ),
62 | ),
63 | ),
64 | ],
65 | ),
66 | ),
67 | ),
68 | );
69 | }
70 | }
--------------------------------------------------------------------------------
/lib/1_tap_effects/tap_area.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/cupertino.dart';
2 | import 'package:flutter/foundation.dart';
3 | import 'package:flutter/material.dart';
4 |
5 | class TapArea extends StatefulWidget {
6 | final Widget child;
7 | final GestureTapCallback? onTap;
8 | final GestureTapCallback? onLongTap;
9 | final double borderRadius;
10 | final EdgeInsets? padding;
11 |
12 | const TapArea({
13 | super.key,
14 | required this.child,
15 | required this.onTap,
16 | this.onLongTap,
17 | this.padding,
18 | this.borderRadius = 0,
19 | });
20 |
21 | @override
22 | State createState() => defaultTargetPlatform == TargetPlatform.iOS
23 | ? _TapAreaIosState()
24 | : _TapAreaAndroidState();
25 | }
26 |
27 | class _TapAreaAndroidState extends State {
28 | @override
29 | Widget build(BuildContext context) {
30 | final content = Padding(
31 | padding: widget.padding ?? EdgeInsets.zero,
32 | child: widget.child,
33 | );
34 |
35 | if (widget.onTap == null && widget.onLongTap == null) return content;
36 |
37 | return Material(
38 | color: Colors.transparent,
39 | clipBehavior: Clip.none,
40 | borderRadius: BorderRadius.circular(widget.borderRadius),
41 | child: InkWell(
42 | borderRadius: BorderRadius.circular(widget.borderRadius),
43 | onTap: widget.onTap,
44 | onLongPress: widget.onLongTap,
45 | child: content,
46 | ),
47 | );
48 | }
49 | }
50 |
51 | class _TapAreaIosState extends State {
52 | bool _isDown = false;
53 |
54 | @override
55 | Widget build(BuildContext context) {
56 | final content = Padding(
57 | padding: widget.padding ?? EdgeInsets.zero,
58 | child: widget.child,
59 | );
60 |
61 | if (widget.onTap == null && widget.onLongTap == null) return content;
62 |
63 | return GestureDetector(
64 | onTapDown: (_) {
65 | setState(() {
66 | _isDown = true;
67 | });
68 | },
69 | onTapCancel: () {
70 | setState(() {
71 | _isDown = false;
72 | });
73 | },
74 | onTap: () {
75 | setState(() {
76 | _isDown = false;
77 | });
78 | widget.onTap!();
79 | },
80 | onLongPress: widget.onLongTap,
81 | child: Focus(
82 | child: Opacity(
83 | opacity: _isDown ? 0.7 : 1.0,
84 | child: content,
85 | ),
86 | ),
87 | );
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/lib/1_tap_effects/tap_area_example.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 | import 'package:flutter_ui_examples/1_tap_effects/tap_area.dart';
3 |
4 | class TapAreaExample extends StatelessWidget {
5 | const TapAreaExample({super.key});
6 |
7 | @override
8 | Widget build(BuildContext context) {
9 | return Scaffold(
10 | backgroundColor: Theme.of(context).colorScheme.secondary,
11 | body: SafeArea(
12 | child: Center(
13 | child: Column(
14 | children: [
15 | Card(
16 | margin: const EdgeInsets.all(16),
17 | child: TapArea(
18 | onTap: () {},
19 | borderRadius: 12,
20 | padding: const EdgeInsets.all(16),
21 | child: const ListTile(
22 | leading: Icon(Icons.data_object),
23 | title: Text("Title"),
24 | subtitle: Text("Subtitle"),
25 | trailing: Text("30.04.2024"),
26 | ),
27 | ),
28 | ),
29 | Card(
30 | margin: const EdgeInsets.all(16),
31 | child: TapArea(
32 | onTap: () {},
33 | borderRadius: 12,
34 | padding: const EdgeInsets.all(16),
35 | child: const ListTile(
36 | leading: Icon(Icons.data_object),
37 | title: Text("Title"),
38 | subtitle: Text("Subtitle"),
39 | trailing: Text("30.04.2024"),
40 | ),
41 | ),
42 | ),
43 | ],
44 | ),
45 | ),
46 | ),
47 | );
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/lib/2_adaptive_refresh_indicator/adaptive_refresh_indicator.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/cupertino.dart';
2 | import 'package:flutter/foundation.dart';
3 | import 'package:flutter/material.dart';
4 |
5 | class AdaptiveRefreshIdicator extends StatelessWidget {
6 | final Widget child;
7 | final Future Function() onRefresh;
8 |
9 | const AdaptiveRefreshIdicator({
10 | super.key,
11 | required this.child,
12 | required this.onRefresh,
13 | });
14 |
15 | @override
16 | Widget build(BuildContext context) {
17 | if (defaultTargetPlatform == TargetPlatform.iOS) {
18 | return _IOSAdaptiveRefreshIdicator(
19 | onRefresh: onRefresh, key: key, child: child);
20 | }
21 | return _AndroidAdaptiveRefreshIdicator(
22 | onRefresh: onRefresh, key: key, child: child);
23 | }
24 | }
25 |
26 | class _AndroidAdaptiveRefreshIdicator extends StatelessWidget {
27 | final Widget child;
28 | final Future Function() onRefresh;
29 |
30 | const _AndroidAdaptiveRefreshIdicator({
31 | super.key,
32 | required this.child,
33 | required this.onRefresh,
34 | });
35 |
36 | @override
37 | Widget build(BuildContext context) {
38 | return RefreshIndicator(
39 | onRefresh: onRefresh, child: SingleChildScrollView(child: child));
40 | }
41 | }
42 |
43 | class _IOSAdaptiveRefreshIdicator extends StatelessWidget {
44 | final Widget child;
45 | final Future Function() onRefresh;
46 |
47 | const _IOSAdaptiveRefreshIdicator({
48 | super.key,
49 | required this.child,
50 | required this.onRefresh,
51 | });
52 |
53 | @override
54 | Widget build(BuildContext context) {
55 | return CustomScrollView(
56 | physics: const BouncingScrollPhysics(
57 | parent: AlwaysScrollableScrollPhysics(),
58 | ),
59 | slivers: [
60 | SliverToBoxAdapter(
61 | child: Container(height: 100, width: 100, color: Colors.red),
62 | ),
63 | CupertinoSliverRefreshControl(
64 | onRefresh: onRefresh,
65 | ),
66 | SliverToBoxAdapter(
67 | child: child,
68 | )
69 | ],
70 | );
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/lib/2_adaptive_refresh_indicator/adaptive_refresh_indicator_example.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 | import 'package:flutter_ui_examples/2_adaptive_refresh_indicator/adaptive_refresh_indicator.dart';
3 |
4 | class AdaptiveRefreshIndicatorExample extends StatelessWidget {
5 | const AdaptiveRefreshIndicatorExample({super.key});
6 |
7 | @override
8 | Widget build(BuildContext context) {
9 | return Scaffold(
10 | appBar: AppBar(title: const Text("Refresh page")),
11 | body: AdaptiveRefreshIdicator(
12 | child: Column(children: [
13 | ...List.generate(
14 | 20,
15 | (index) => const ListTile(
16 | title: Text("item"),
17 | ),
18 | )
19 | ]),
20 | onRefresh: () async {
21 | await Future.delayed(const Duration(seconds: 3));
22 | }),
23 | );
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/lib/2_adaptive_refresh_indicator_advanced/adaptive_refresh_indicator.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/cupertino.dart';
2 | import 'package:flutter/foundation.dart';
3 | import 'package:flutter/material.dart';
4 |
5 | class AdaptiveRefreshIdicator2 extends StatelessWidget {
6 | final Widget? child;
7 | final List? slivers;
8 | final Future Function() onRefresh;
9 |
10 | const AdaptiveRefreshIdicator2({
11 | super.key,
12 | this.child,
13 | this.slivers,
14 | required this.onRefresh,
15 | }) : assert((slivers != null) != (child != null));
16 |
17 | @override
18 | Widget build(BuildContext context) {
19 | if (defaultTargetPlatform == TargetPlatform.iOS) {
20 | return _SliverAdaptiveRefreshIdicator(
21 | onRefresh: onRefresh,
22 | key: key,
23 | slivers: slivers,
24 | child: child,
25 | );
26 | }
27 |
28 | return _AndroidAdaptiveRefreshIdicator(
29 | onRefresh: onRefresh,
30 | key: key,
31 | slivers: slivers,
32 | child: child,
33 | );
34 | }
35 | }
36 |
37 | class _AndroidAdaptiveRefreshIdicator extends StatelessWidget {
38 | final Widget? child;
39 | final List? slivers;
40 | final Future Function() onRefresh;
41 |
42 | const _AndroidAdaptiveRefreshIdicator({
43 | super.key,
44 | this.child,
45 | this.slivers,
46 | required this.onRefresh,
47 | });
48 |
49 | @override
50 | Widget build(BuildContext context) {
51 | final content = slivers != null
52 | ? _SliverAdaptiveRefreshIdicator(
53 | onRefresh: onRefresh,
54 | key: key,
55 | slivers: slivers,
56 | isCupertinoSliverRefreshControlShown: false,
57 | child: child,
58 | )
59 | : SingleChildScrollView(child: child);
60 |
61 | return RefreshIndicator(onRefresh: onRefresh, child: content);
62 | }
63 | }
64 |
65 | class _SliverAdaptiveRefreshIdicator extends StatelessWidget {
66 | final Widget? child;
67 | final Future Function() onRefresh;
68 | final List? slivers;
69 | final bool isCupertinoSliverRefreshControlShown;
70 |
71 | const _SliverAdaptiveRefreshIdicator({
72 | super.key,
73 | this.slivers,
74 | this.child,
75 | this.isCupertinoSliverRefreshControlShown = true,
76 | required this.onRefresh,
77 | });
78 |
79 | @override
80 | Widget build(BuildContext context) {
81 | return CustomScrollView(
82 | physics: isCupertinoSliverRefreshControlShown
83 | ? const BouncingScrollPhysics(
84 | parent: AlwaysScrollableScrollPhysics(),
85 | )
86 | : null,
87 | slivers: [
88 | if (isCupertinoSliverRefreshControlShown)
89 | SliverSafeArea(
90 | sliver: CupertinoSliverRefreshControl(
91 | onRefresh: onRefresh,
92 | ),
93 | ),
94 | ...?slivers,
95 | if (child != null)
96 | SliverToBoxAdapter(
97 | child: child,
98 | )
99 | ],
100 | );
101 | }
102 | }
103 |
--------------------------------------------------------------------------------
/lib/2_adaptive_refresh_indicator_advanced/adaptive_refresh_indicator_example.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 | import 'adaptive_refresh_indicator.dart';
3 |
4 | class AdaptiveRefreshIndicatorExample2 extends StatelessWidget {
5 | const AdaptiveRefreshIndicatorExample2({super.key});
6 |
7 | @override
8 | Widget build(BuildContext context) {
9 | return Scaffold(
10 | body: AdaptiveRefreshIdicator2(
11 | slivers: [
12 | SliverList.builder(
13 | itemCount: 1000,
14 | itemBuilder: (context, index) {
15 | return Card(
16 | child: Text(index.toString()),
17 | );
18 | },
19 | )
20 | ],
21 | onRefresh: () async {
22 | await Future.delayed(const Duration(seconds: 3));
23 | }),
24 | );
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/lib/3_list_view_mistakes/list_view_extent.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/cupertino.dart';
2 | import 'package:flutter/material.dart';
3 |
4 | class ListViewExtent extends StatelessWidget {
5 | const ListViewExtent({super.key});
6 |
7 | @override
8 | Widget build(BuildContext context) {
9 | return Scaffold(
10 | body: SafeArea(
11 | child: ListView.builder(
12 | itemCount: 1000,
13 | prototypeItem: const Card(child: Text("")),
14 | itemBuilder: (context, index) {
15 | return Card(child: Text(index.toString()));
16 | },
17 | ),
18 | ),
19 | );
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/lib/3_list_view_mistakes/list_view_keys.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 |
3 | final _globalKeys = List.generate(200, (_) => GlobalKey());
4 |
5 | class ListViewKeys extends StatelessWidget {
6 | final bool useGlobalKeys;
7 | final bool useValueKeys;
8 |
9 | const ListViewKeys._({super.key, required this.useGlobalKeys, required this.useValueKeys});
10 |
11 | factory ListViewKeys.globalKeys() {
12 | return const ListViewKeys._(useGlobalKeys: true, useValueKeys: false);
13 | }
14 |
15 | factory ListViewKeys.valueKeys() {
16 | return const ListViewKeys._(useGlobalKeys: false, useValueKeys: true);
17 | }
18 |
19 | factory ListViewKeys.noKeys() {
20 | return const ListViewKeys._(useGlobalKeys: false, useValueKeys: false);
21 | }
22 |
23 | @override
24 | Widget build(BuildContext context) {
25 | return Scaffold(
26 | appBar: AppBar(title: Text("ListView keys")),
27 | body: ListView.builder(
28 | restorationId: 'news_feed',
29 | itemCount: 200,
30 | prototypeItem: const _ListItem(null),
31 | itemBuilder: (context, index) {
32 | if (index == 199) {
33 | return const _ListItem(199, key: ValueKey("last_item"));
34 | }
35 | final key = useGlobalKeys ? _globalKeys[index] : useValueKeys ? ValueKey("item_$index") : null;
36 |
37 | return _ListItem(index, key: key);
38 | },
39 | ),
40 | );
41 | }
42 | }
43 |
44 | class _ListItem extends StatelessWidget {
45 | final int? index;
46 |
47 | const _ListItem(this.index, {super.key});
48 |
49 | @override
50 | Widget build(BuildContext context) {
51 | return Card(
52 | elevation: 4,
53 | surfaceTintColor: Colors.blueAccent.withOpacity(0.2),
54 | child: ListTile(
55 | leading: Image.network("https://external-preview.redd.it/searching-for-flutter-jobs-in-nutshell-v0-9IzaY9JP5-j2YRSPe6FZnaQthG7qpDOn3FgFrp6cy6A.jpg?auto=webp&s=44254c56bbd2555a63ae41f5e3a5729db431bff6"),
56 | title: Text("Item $index"),
57 | subtitle: const Text("Subtitle"),
58 | trailing: const CircularProgressIndicator.adaptive(),
59 | ),
60 | );
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/lib/3_list_view_mistakes/list_view_never_scrollable_slivers.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 |
3 | class ListViewNeverScrollableSlivers extends StatelessWidget {
4 | final bool hasPrototype;
5 |
6 | const ListViewNeverScrollableSlivers({this.hasPrototype = true, super.key});
7 |
8 | @override
9 | Widget build(BuildContext context) {
10 | return Scaffold(
11 | body: SafeArea(
12 | child: CustomScrollView(
13 | key: const Key('scrollable'),
14 | slivers: [
15 | const SliverToBoxAdapter(child: Card(child: Text("Header card"))),
16 | SliverPrototypeExtentList.builder(
17 | itemCount: 1000,
18 | itemBuilder: (context, index) {
19 | print("building item #${index}");
20 | return Card(child: Text(index.toString()));
21 | },
22 | prototypeItem: const Card(child: Text("")),
23 | ),
24 | const SliverToBoxAdapter(
25 | child: Card(
26 | key: ValueKey('last_item'), child: Text("Footer card"))),
27 | ],
28 | ),
29 | ),
30 | );
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/lib/3_list_view_mistakes/list_view_padding.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 |
3 | class ListViewPadding extends StatelessWidget {
4 | const ListViewPadding({super.key});
5 |
6 | @override
7 | Widget build(BuildContext context) {
8 | return Scaffold(
9 | appBar: AppBar(title: Text("ListView with padding"),),
10 | body: SafeArea(
11 | child: ListView.builder(
12 | itemCount: 1000,
13 | padding: const EdgeInsets.all(40),
14 | prototypeItem: const Card(child: Text("")),
15 | itemBuilder: (context, index) {
16 | return Card(child: Text(index.toString()));
17 | },
18 | ),
19 | ),
20 | );
21 | }
22 | }
--------------------------------------------------------------------------------
/lib/4_text_scaling/text_scaling.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 | import 'package:i18n/strings.g.dart';
3 |
4 | class TextScaling extends StatelessWidget {
5 | const TextScaling({super.key});
6 |
7 | @override
8 | Widget build(BuildContext context) {
9 | return Scaffold(
10 | appBar: AppBar(
11 | title: const Text(
12 | "Text Scaling example",
13 | ),
14 | ),
15 | body: SingleChildScrollView(
16 | child: Padding(
17 | padding: Insets.medium(context),
18 | child: Column(
19 | children: [
20 | Row(
21 | children: [
22 | const Text("Hello, User!"),
23 | SizedBox(width: Dimens.large(context)),
24 | Expanded(
25 | child: Text(
26 | Dimens.isSmallWidth(context)
27 | ? t.tasksDoneShort(n: 10, completed: 5)
28 | : t.tasksDone(n: 10, completed: 5),
29 | maxLines: 1,
30 | textAlign: TextAlign.end,
31 | ),
32 | ),
33 | ],
34 | ),
35 | ConstrainedBox(
36 | constraints: const BoxConstraints(minHeight: 100),
37 | child: const Card(
38 | child: Center(
39 | child: Column(
40 | mainAxisAlignment: MainAxisAlignment.center,
41 | children: [
42 | TitleText("Item A", style: TextStyle(fontSize: 30)),
43 | Text("Subtitle", maxLines: 1),
44 | ],
45 | ),
46 | ),
47 | ),
48 | ),
49 | SizedBox(height: Dimens.medium(context)),
50 | const Row(children: [
51 | _RowCard(),
52 | _RowCard(),
53 | _RowCard(),
54 | ]),
55 | const Row(children: [
56 | _RowCardSubtitle(subtitle: "1 user"),
57 | _RowCardSubtitle(subtitle: "3 users"),
58 | _RowCardSubtitle(subtitle: "1234123 users"),
59 | ]),
60 | SizedBox(height: Dimens.medium(context)),
61 | const Text(
62 | "Text C: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
63 | maxLines: 10,
64 | ),
65 | ],
66 | ),
67 | ),
68 | ),
69 | );
70 | }
71 | }
72 |
73 | class _RowCard extends StatelessWidget {
74 | const _RowCard({super.key});
75 |
76 | @override
77 | Widget build(BuildContext context) {
78 | return Expanded(
79 | child: Card(
80 | child: Center(
81 | child: Padding(
82 | padding: Insets.medium(context),
83 | child: TitleText(
84 | "Item B",
85 | style: TextStyle(fontSize: 24),
86 | ),
87 | ),
88 | ),
89 | ),
90 | );
91 | }
92 | }
93 |
94 | class _RowCardSubtitle extends StatelessWidget {
95 | final String subtitle;
96 |
97 | const _RowCardSubtitle({super.key, required this.subtitle});
98 |
99 | @override
100 | Widget build(BuildContext context) {
101 | return Expanded(
102 | child: Card(
103 | child: Center(
104 | child: Padding(
105 | padding: Insets.medium(context),
106 | child: Column(
107 | crossAxisAlignment: CrossAxisAlignment.start,
108 | children: [
109 | TitleText(
110 | "Item D",
111 | style: TextStyle(fontSize: 24),
112 | ),
113 | Text(subtitle, style: TextStyle(fontSize: 11), maxLines: 1)
114 | ],
115 | ),
116 | ),
117 | ),
118 | ),
119 | );
120 | }
121 | }
122 |
123 | class Dimens {
124 | static const smallScreenThreshold = 300;
125 | static bool isSmallWidth(BuildContext context) {
126 | return MediaQuery.of(context).size.width /
127 | MediaQuery.textScalerOf(context).scale(1) <
128 | smallScreenThreshold;
129 | }
130 |
131 | static double small(BuildContext context) => isSmallWidth(context) ? 4 : 8;
132 | static double medium(BuildContext context) => isSmallWidth(context) ? 8 : 16;
133 | static double large(BuildContext context) => isSmallWidth(context) ? 16 : 32;
134 | }
135 |
136 | class Insets {
137 | static EdgeInsets small(BuildContext context) =>
138 | EdgeInsets.all(Dimens.small(context));
139 |
140 | static EdgeInsets medium(BuildContext context) =>
141 | EdgeInsets.all(Dimens.medium(context));
142 |
143 | static EdgeInsets large(BuildContext context) =>
144 | EdgeInsets.all(Dimens.large(context));
145 | }
146 |
147 | class TitleText extends StatelessWidget {
148 | final String text;
149 | final TextStyle style;
150 |
151 | const TitleText(this.text, {required this.style, super.key});
152 |
153 | static const double maxRealFontSize = 30;
154 |
155 | @override
156 | Widget build(BuildContext context) {
157 | if (MediaQuery.textScalerOf(context).scale(style.fontSize!) >
158 | maxRealFontSize) {
159 | return Text(
160 | text,
161 | style: style.copyWith(
162 | fontSize: maxRealFontSize / MediaQuery.textScalerOf(context).scale(1),
163 | ),
164 | );
165 | }
166 | return Text(text, style: style);
167 | }
168 | }
169 |
170 |
171 | // "tasksDone(rich)": {
172 | // "one": "You have done $completed of $n tasks",
173 | // "other": "You have done $completed of $n tasks"
174 | // },
175 | // "tasksDone(rich)": {
176 | // "one": "$completed/$n tasks done",
177 | // "other": "$completed/$n tasks done"
178 | // },
--------------------------------------------------------------------------------
/lib/5_localization/localization_example.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 | import 'package:google_fonts/google_fonts.dart';
3 | import 'package:i18n/strings.g.dart';
4 | import 'package:intl/intl.dart';
5 | import 'package:styled_text/styled_text.dart';
6 |
7 | class LocalizationExample extends StatefulWidget {
8 | const LocalizationExample({super.key});
9 |
10 | @override
11 | State createState() => _LocalizationExampleState();
12 | }
13 |
14 | class _LocalizationExampleState extends State {
15 | @override
16 | void initState() {
17 | super.initState();
18 | _printCurrencies();
19 | WidgetsBinding.instance.addPostFrameCallback((_) => _printDates());
20 | }
21 |
22 | @override
23 | Widget build(BuildContext context) {
24 | return Scaffold(
25 | appBar: AppBar(title: Text("Localization example")),
26 | body: Column(
27 | children: [
28 | StyledText(
29 | text: t.agreeWithTerms,
30 | style: Theme.of(context).textTheme.bodyMedium,
31 | tags: {
32 | 'a': StyledTextActionTag(
33 | (String? text, Map attrs) {
34 | final action = attrs['action'];
35 | switch (action) {
36 | case 'OPEN_TC':
37 | _openTC();
38 | case 'OPEN_PP':
39 | _openPP();
40 | }
41 | },
42 | style: Theme.of(context).textTheme.bodyMedium!.copyWith(
43 | color: Theme.of(context).primaryColor,
44 | decoration: TextDecoration.underline),
45 | )
46 | },
47 | ),
48 | Text(t.usersOnline(n: 3)),
49 | Text("köpək", style: GoogleFonts.aDLaMDisplay(fontSize: 30))
50 | ],
51 | ),
52 | );
53 | }
54 |
55 | void _openTC() {
56 | print("open TC");
57 | }
58 |
59 | void _openPP() {
60 | print("open PP");
61 | }
62 |
63 | void _printDates() {
64 | final date = DateTime.now();
65 | format(String locale) => "$locale: ${DateFormat.yMMMEd(locale).format(date)}}";
66 | print(format("en_US"));
67 | print(format("en_GB"));
68 | print(format("et_EE"));
69 | print(format("fi_FI"));
70 | print(format("ar_QA"));
71 | print(TimeOfDay.now().format(context));
72 | }
73 |
74 | void _printCurrencies() {
75 | print(NumberFormat.simpleCurrency(locale: 'en_US', name: 'USD').format(199.99));
76 | print(NumberFormat.simpleCurrency(locale: 'en_GB', name: 'GBP').format(199.99));
77 | print(NumberFormat.simpleCurrency(locale: 'es_ES', name: 'EUR').format(199.99));
78 | }
79 |
80 | String explicitFormat(String currencyCode, String? locale, num amount) {
81 | final shortFormat = NumberFormat.simpleCurrency(locale: locale, name: currencyCode).format(amount);
82 |
83 | return "$shortFormat $currencyCode";
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/lib/6_widget_state_property/card_example.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 |
3 | class CardExample extends StatefulWidget {
4 | const CardExample({super.key});
5 |
6 | @override
7 | State createState() => _CardExampleState();
8 | }
9 |
10 | class _CardExampleState extends State {
11 | final _controller = WidgetStatesController();
12 |
13 | @override
14 | Widget build(BuildContext context) {
15 | return ValueListenableBuilder(
16 | valueListenable: _controller,
17 | builder: (context, states, _) {
18 | return Card(
19 | elevation: states.contains(WidgetState.hovered) ? 4 : 0,
20 | child: Padding(
21 | padding: const EdgeInsets.all(16),
22 | child: Column(
23 | children: [
24 | const Text("Text"),
25 | TextButton(
26 | statesController: _controller,
27 | onPressed: _onPressed,
28 | child: const Text("Button"),
29 | )
30 | ],
31 | ),
32 | ),
33 | );
34 | }
35 | );
36 | }
37 |
38 | void _onPressed() {
39 |
40 | }
41 | }
42 |
43 |
--------------------------------------------------------------------------------
/lib/6_widget_state_property/selectable_button.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 |
3 | class SelectableButton extends StatefulWidget {
4 | final bool isSelected;
5 | final VoidCallback? onPressed;
6 |
7 | const SelectableButton({
8 | super.key,
9 | required this.isSelected,
10 | this.onPressed,
11 | });
12 |
13 | @override
14 | State createState() => _SelectableButtonState();
15 | }
16 |
17 | const Color _white = Color(0xFFFFFFFF);
18 | const Color _darkBlue = Color(0xFF212936);
19 | const Color _green = Color(0xFF43946C);
20 |
21 | class _SelectableButtonState extends State
22 | with SingleTickerProviderStateMixin {
23 | late AnimationController _blinkAnimationController;
24 | late WidgetStatesController _statesController;
25 |
26 | bool get _isSelected =>
27 | _statesController.value.contains(WidgetState.selected);
28 |
29 | @override
30 | void initState() {
31 | super.initState();
32 | _statesController = WidgetStatesController()
33 | ..update(
34 | WidgetState.selected,
35 | widget.isSelected,
36 | );
37 |
38 | _blinkAnimationController = AnimationController(
39 | vsync: this,
40 | duration: const Duration(seconds: 1),
41 | )..repeat(reverse: true);
42 | }
43 |
44 | @override
45 | Widget build(BuildContext context) {
46 | return TextButton(
47 | statesController: _statesController,
48 | clipBehavior: Clip.none,
49 | style: ButtonStyle(
50 | padding: const WidgetStatePropertyAll(EdgeInsets.zero),
51 | shape: WidgetStateProperty.resolveWith((states) {
52 | return RoundedRectangleBorder(
53 | borderRadius: BorderRadius.circular(5),
54 | );
55 | }),
56 | backgroundBuilder: (context, states, child) {
57 | final color =
58 | states.contains(WidgetState.selected) ? _green : _darkBlue;
59 | return AnimatedContainer(
60 | duration: kThemeAnimationDuration,
61 | decoration: BoxDecoration(
62 | color: color,
63 | borderRadius: BorderRadius.circular(5),
64 | ),
65 | child: child,
66 | );
67 | },
68 | splashFactory: NoSplash.splashFactory,
69 | animationDuration: kThemeAnimationDuration,
70 | elevation: WidgetStateProperty.resolveWith((states) {
71 | if (states.contains(WidgetState.pressed)) {
72 | return 0;
73 | }
74 |
75 | return 8;
76 | }),
77 | shadowColor: WidgetStateProperty.resolveWith((states) {
78 | if (states.contains(WidgetState.selected)) {
79 | return _green.withValues(alpha: 0.5);
80 | }
81 |
82 | return _darkBlue.withValues(alpha: 0.5);
83 | }),
84 | foregroundColor: WidgetStateProperty.resolveWith((states) {
85 | if (states.contains(WidgetState.pressed)) {
86 | return _white.withValues(alpha: 0.5);
87 | }
88 |
89 | return Colors.white;
90 | }),
91 | foregroundBuilder: (context, states, child) {
92 | if (states.contains(WidgetState.hovered)) {
93 | return DecoratedBox(
94 | decoration: BoxDecoration(
95 | color: _white.withValues(alpha: 0.2),
96 | backgroundBlendMode: BlendMode.overlay,
97 | ),
98 | child: child,
99 | );
100 | }
101 |
102 | return child!;
103 | },
104 | ),
105 | onPressed: () {
106 | _statesController.update(WidgetState.selected, !_isSelected);
107 | widget.onPressed?.call();
108 | },
109 | child: Padding(
110 | padding: const EdgeInsets.symmetric(
111 | horizontal: 16,
112 | vertical: 8,
113 | ),
114 | child: ListenableBuilder(
115 | listenable: _statesController,
116 | builder: (context, _) => Row(
117 | mainAxisSize: MainAxisSize.min,
118 | children: [
119 | AnimatedCrossFade(
120 | firstChild: const _IndicatorOff(),
121 | secondChild: _IndicatorOn(
122 | animationController: _blinkAnimationController),
123 | crossFadeState: _isSelected
124 | ? CrossFadeState.showSecond
125 | : CrossFadeState.showFirst,
126 | duration: kThemeAnimationDuration,
127 | ),
128 | const SizedBox(width: 8),
129 | MaxWidthPreservingSwitch(
130 | firstChild: Text(
131 | "System Off",
132 | ),
133 | secondChild: Text(
134 | "System On",
135 | ),
136 | showFirst: !_isSelected,
137 | ),
138 | ],
139 | ),
140 | ),
141 | ),
142 | );
143 | }
144 |
145 | // @override
146 | // void didUpdateWidget(ButtonStyleButton oldWidget) {
147 | // super.didUpdateWidget(oldWidget);
148 | // if (widget.statesController != oldWidget.statesController) {
149 | // oldWidget.statesController?.removeListener(handleStatesControllerChange);
150 | // if (widget.statesController != null) {
151 | // internalStatesController?.dispose();
152 | // internalStatesController = null;
153 | // }
154 | // initStatesController();
155 | // }
156 | // if (widget.enabled != oldWidget.enabled) {
157 | // statesController.update(MaterialState.disabled, !widget.enabled);
158 | // if (!widget.enabled) {
159 | // // The button may have been disabled while a press gesture is currently underway.
160 | // statesController.update(MaterialState.pressed, false);
161 | // }
162 | // }
163 | // }
164 | }
165 |
166 | class _IndicatorOff extends StatelessWidget {
167 | const _IndicatorOff({Key? key}) : super(key: key);
168 |
169 | @override
170 | Widget build(BuildContext context) {
171 | return Container(
172 | width: 14,
173 | height: 14,
174 | decoration: BoxDecoration(
175 | shape: BoxShape.circle,
176 | border: Border.all(
177 | color: Colors.white38,
178 | width: 2,
179 | ),
180 | ),
181 | );
182 | }
183 | }
184 |
185 | class _IndicatorOn extends StatefulWidget {
186 | final AnimationController animationController;
187 | const _IndicatorOn({
188 | Key? key,
189 | required this.animationController,
190 | }) : super(key: key);
191 |
192 | @override
193 | State<_IndicatorOn> createState() => _IndicatorOnState();
194 | }
195 |
196 | class _IndicatorOnState extends State<_IndicatorOn> {
197 | late Animation _opacityAnimation;
198 |
199 | @override
200 | void initState() {
201 | super.initState();
202 |
203 | _opacityAnimation =
204 | Tween(begin: 0.3, end: 1.0).animate(widget.animationController);
205 | }
206 |
207 | @override
208 | Widget build(BuildContext context) {
209 | return AnimatedBuilder(
210 | animation: _opacityAnimation,
211 | builder: (context, child) {
212 | return AnimatedOpacity(
213 | opacity: _opacityAnimation.value,
214 | duration: const Duration(milliseconds: 200),
215 | child: Container(
216 | width: 14,
217 | height: 14,
218 | decoration: const BoxDecoration(
219 | shape: BoxShape.circle,
220 | color: Colors.white,
221 | ),
222 | ),
223 | );
224 | },
225 | );
226 | }
227 | }
228 |
229 | class MaxWidthPreservingSwitch extends StatelessWidget {
230 | final Widget firstChild;
231 | final Widget secondChild;
232 | final bool showFirst;
233 |
234 | const MaxWidthPreservingSwitch({
235 | Key? key,
236 | required this.firstChild,
237 | required this.secondChild,
238 | required this.showFirst,
239 | }) : super(key: key);
240 |
241 | @override
242 | Widget build(BuildContext context) {
243 | return Stack(
244 | alignment: Alignment.center,
245 | children: [
246 | // Invisible placeholder to establish maximum width
247 |
248 | Opacity(opacity: 0, child: firstChild),
249 | Opacity(opacity: 0, child: secondChild),
250 |
251 | // Visible child
252 | showFirst ? firstChild : secondChild,
253 | ],
254 | );
255 | }
256 | }
257 |
--------------------------------------------------------------------------------
/lib/6_widget_state_property/tap_area_2.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/foundation.dart';
2 | import 'package:flutter/material.dart';
3 |
4 | class TapArea2 extends StatefulWidget {
5 | final Widget child;
6 | final GestureTapCallback? onTap;
7 | final GestureTapCallback? onLongTap;
8 | final double borderRadius;
9 | final EdgeInsets? padding;
10 | final TapAreaStyle? style;
11 |
12 | const TapArea2({
13 | super.key,
14 | required this.child,
15 | required this.onTap,
16 | this.onLongTap,
17 | this.style,
18 | this.padding,
19 | this.borderRadius = 0,
20 | });
21 |
22 | @override
23 | // ignore: no_logic_in_create_state
24 | State createState() => switch(defaultTargetPlatform) {
25 | TargetPlatform.android => _TapAreaAndroidState(),
26 | TargetPlatform.iOS => _TapAreaIosState(),
27 | _ => _TapAreaWebState()
28 | };
29 | }
30 |
31 | class _TapAreaAndroidState extends State {
32 | @override
33 | Widget build(BuildContext context) {
34 | final content = Padding(
35 | padding: widget.padding ?? EdgeInsets.zero,
36 | child: widget.child,
37 | );
38 |
39 | if (widget.onTap == null && widget.onLongTap == null) return content;
40 |
41 | return Material(
42 | color: Colors.transparent,
43 | clipBehavior: Clip.none,
44 | borderRadius: BorderRadius.circular(widget.borderRadius),
45 | child: InkWell(
46 | borderRadius: BorderRadius.circular(widget.borderRadius),
47 | onTap: widget.onTap,
48 | onLongPress: widget.onLongTap,
49 | child: content,
50 | ),
51 | );
52 | }
53 | }
54 |
55 | class _TapAreaIosState extends State {
56 | bool _isDown = false;
57 |
58 | @override
59 | Widget build(BuildContext context) {
60 | final content = Padding(
61 | padding: widget.padding ?? EdgeInsets.zero,
62 | child: widget.child,
63 | );
64 |
65 | if (widget.onTap == null && widget.onLongTap == null) return content;
66 |
67 | return GestureDetector(
68 | onTapDown: (_) {
69 | setState(() {
70 | _isDown = true;
71 | });
72 | },
73 | onTapCancel: () {
74 | setState(() {
75 | _isDown = false;
76 | });
77 | },
78 | onTap: () {
79 | setState(() {
80 | _isDown = false;
81 | });
82 | widget.onTap!();
83 | },
84 | onLongPress: widget.onLongTap,
85 | child: Focus(
86 | child: Opacity(
87 | opacity: _isDown ? 0.7 : 1.0,
88 | child: content,
89 | ),
90 | ),
91 | );
92 | }
93 | }
94 |
95 | class _TapAreaWebState extends State {
96 | final _statesController = WidgetStatesController();
97 |
98 | @override
99 | Widget build(BuildContext context) {
100 | final content = Padding(
101 | padding: widget.padding ?? EdgeInsets.zero,
102 | child: widget.child,
103 | );
104 |
105 | if (widget.onTap == null && widget.onLongTap == null) return content;
106 |
107 | return ListenableBuilder(
108 | listenable: _statesController,
109 | builder: (context, _) {
110 | final resolvedOpacity =
111 | widget.style?.opacity.resolve(_statesController.value) ?? 1.0;
112 | final resolvedHighlightOpacity = widget.style?.foregroundHighlight
113 | .resolve(_statesController.value) ??
114 | 1.0;
115 |
116 | return MouseRegion(
117 | onEnter: (_) {
118 | _statesController.update(WidgetState.hovered, true);
119 | },
120 | onExit: (_) {
121 | _statesController.update(WidgetState.hovered, false);
122 | },
123 | child: GestureDetector(
124 | onTapDown: (_) {
125 | _statesController.update(WidgetState.pressed, true);
126 | },
127 | onTapCancel: () {
128 | _statesController.update(WidgetState.pressed, false);
129 | },
130 | onTap: () {
131 | _statesController.update(WidgetState.pressed, false);
132 |
133 | widget.onTap!();
134 | },
135 | onLongPress: widget.onLongTap,
136 | child: Focus(
137 | child: ColoredBox(
138 | color:
139 | Colors.deepPurple.withOpacity(resolvedHighlightOpacity),
140 | child: Opacity(
141 | opacity: resolvedOpacity,
142 | child: content,
143 | ),
144 | ),
145 | ),
146 | ),
147 | );
148 | });
149 | }
150 | }
151 |
152 | class TapAreaThemeData {
153 | final TapAreaStyle style;
154 |
155 | TapAreaThemeData(this.style);
156 | }
157 |
158 | class TapAreaStyle {
159 | final WidgetStateProperty opacity;
160 | final WidgetStateProperty foregroundHighlight;
161 |
162 | TapAreaStyle({required this.opacity, required this.foregroundHighlight});
163 | }
164 |
--------------------------------------------------------------------------------
/lib/6_widget_state_property/widget_state_property_example.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 | import 'package:flutter_ui_examples/6_widget_state_property/selectable_button.dart';
3 | import 'package:flutter_ui_examples/6_widget_state_property/tap_area_2.dart';
4 |
5 | import 'card_example.dart';
6 |
7 | class WidgetStatePropertyExample extends StatefulWidget {
8 | const WidgetStatePropertyExample({super.key});
9 |
10 | @override
11 | State createState() =>
12 | _WidgetStatePropertyExampleState();
13 | }
14 |
15 | class _WidgetStatePropertyExampleState
16 | extends State {
17 | final _statesController = WidgetStatesController();
18 |
19 | @override
20 | Widget build(BuildContext context) {
21 | return Scaffold(
22 | body: SafeArea(
23 | child: Padding(
24 | padding: const EdgeInsets.all(40),
25 | child: Column(
26 | children: [
27 | const SelectableButton(isSelected: false),
28 | const SizedBox(height: 40),
29 | const CardExample(),
30 | const SizedBox(height: 40),
31 | _ButtonExample(statesController: _statesController),
32 | const SizedBox(height: 40),
33 | TapArea2(
34 | style: TapAreaStyle(
35 | opacity: WidgetStateProperty.resolveWith(
36 | (states) {
37 | if (states.contains(WidgetState.pressed)) {
38 | return 0.5;
39 | }
40 | if (states.contains(WidgetState.hovered)) {
41 | return 0.9;
42 | }
43 | return 1.0;
44 | },
45 | ),
46 | foregroundHighlight: WidgetStateProperty.resolveWith(
47 | (states) {
48 | if (states.contains(WidgetState.hovered)) {
49 | return 0.1;
50 | }
51 | return 0.0;
52 | },
53 | ),
54 | ),
55 | padding: EdgeInsets.all(20),
56 | child: Text("Tap area"),
57 | onTap: () {},
58 | ),
59 | ],
60 | ),
61 | ),
62 | ),
63 | );
64 | }
65 | }
66 |
67 | class _ButtonExample extends StatelessWidget {
68 | const _ButtonExample({
69 | super.key,
70 | required WidgetStatesController statesController,
71 | }) : _statesController = statesController;
72 |
73 | final WidgetStatesController _statesController;
74 |
75 | @override
76 | Widget build(BuildContext context) {
77 | return TextButton(
78 | statesController: _statesController,
79 | style: ButtonStyle(side: WidgetStateProperty.resolveWith((states) {
80 | if (states.contains(WidgetState.pressed)) {
81 | return const BorderSide(color: Colors.black);
82 | }
83 | if (states.contains(WidgetState.hovered)) {
84 | return const BorderSide(color: Colors.deepPurple);
85 | }
86 | return null;
87 | }), backgroundColor: WidgetStateProperty.resolveWith((states) {
88 | if (states.contains(WidgetState.hovered)) {
89 | return Colors.black12;
90 | }
91 | return Colors.transparent;
92 | })),
93 | onPressed: () {},
94 | child: Text("ABC"),
95 | );
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/lib/7_images/images_example.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 |
3 | class ImagesExample extends StatelessWidget {
4 | final Widget child;
5 | const ImagesExample(this.child, {super.key});
6 |
7 | @override
8 | Widget build(BuildContext context) {
9 | return Scaffold(
10 | appBar: AppBar(
11 | title: Text("Images Example"),
12 | ),
13 | body: Column(
14 | children: [
15 | child,
16 | TextButton(
17 | onPressed: () {
18 | ScaffoldMessenger.of(context).showSnackBar(
19 | SnackBar(
20 | content: Text(
21 | PaintingBinding.instance.imageCache.currentSizeBytes
22 | .toString(),
23 | ),
24 | ),
25 | );
26 | },
27 | child: Text("Check cache"),
28 | )
29 | ],
30 | ),
31 | );
32 | }
33 | }
34 |
35 |
36 |
--------------------------------------------------------------------------------
/lib/7_images/images_example_list.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 | import 'package:flutter/services.dart';
3 | import 'package:flutter_svg/svg.dart';
4 | import 'package:flutter_ui_examples/7_images/images_example.dart';
5 |
6 | class ImagesExampleList extends StatelessWidget {
7 | const ImagesExampleList({super.key});
8 |
9 | @override
10 | Widget build(BuildContext context) {
11 | return Scaffold(
12 | appBar: AppBar(
13 | title: Text("Image examples"),
14 | ),
15 | body: Column(
16 | children: [
17 | TextButton(
18 | child: Text("No cacheHeight"),
19 | onPressed: () {
20 | Navigator.push(context, MaterialPageRoute(
21 | builder: (context) {
22 | return ImagesExample(_OriginalSizedImage());
23 | },
24 | ));
25 | },
26 | ),
27 | TextButton(
28 | child: Text("cacheHeight: 100"),
29 | onPressed: () {
30 | Navigator.push(context, MaterialPageRoute(
31 | builder: (context) {
32 | return ImagesExample(_CacheHeightImage(100));
33 | },
34 | ));
35 | },
36 | ),
37 | TextButton(
38 | child: Text("cacheHeight: 500"),
39 | onPressed: () {
40 | Navigator.push(context, MaterialPageRoute(
41 | builder: (context) {
42 | return ImagesExample(_CacheHeightImage(500));
43 | },
44 | ));
45 | },
46 | ),
47 | TextButton(
48 | child: Text("Opacity Example"),
49 | onPressed: () {
50 | Navigator.push(context, MaterialPageRoute(
51 | builder: (context) {
52 | return _OpacityExample();
53 | },
54 | ));
55 | },
56 | ),
57 | TextButton(
58 | child: Text("No Opacity Example"),
59 | onPressed: () {
60 | Navigator.push(context, MaterialPageRoute(
61 | builder: (context) {
62 | return _NoOpacityExample();
63 | },
64 | ));
65 | },
66 | ),
67 | TextButton(
68 | child: const Text("Precache image"),
69 | onPressed: () async {
70 | cacheSize() => PaintingBinding.instance.imageCache.currentSizeBytes.toString();
71 | print(cacheSize());
72 | final asset = Image.asset(
73 | "assets/6392956.jpg",
74 | height: 100,
75 | width: 300,
76 | cacheHeight: (100 * MediaQuery.of(context).devicePixelRatio).toInt(),
77 | );
78 | await precacheImage(asset.image, context);
79 | print(cacheSize());
80 | },
81 | )
82 | ],
83 | ),
84 | );
85 | }
86 | }
87 |
88 | class _OpacityExample extends StatelessWidget {
89 | const _OpacityExample({super.key});
90 |
91 | @override
92 | Widget build(BuildContext context) {
93 | return Column(
94 | children: [
95 | for (int i = 0; i < 10; i++)
96 | Opacity(
97 | opacity: 0.5,
98 | child: Image.asset(
99 | "assets/6392956.jpg",
100 | height: 100,
101 | width: 300,
102 | cacheHeight:
103 | (100 * MediaQuery.of(context).devicePixelRatio).toInt(),
104 | ),
105 | ),
106 | ],
107 | );
108 | }
109 | }
110 |
111 | class _NoOpacityExample extends StatelessWidget {
112 | const _NoOpacityExample({super.key});
113 |
114 | @override
115 | Widget build(BuildContext context) {
116 | return Column(
117 | children: [
118 | for (int i = 0; i < 10; i++)
119 | Image.asset(
120 | "assets/6392956.jpg",
121 | height: 100,
122 | width: 300,
123 | color: Colors.white.withOpacity(0.5),
124 | colorBlendMode: BlendMode.modulate,
125 | cacheHeight:
126 | (100 * MediaQuery.of(context).devicePixelRatio).toInt(),
127 | ),
128 | ],
129 | );
130 | }
131 | }
132 |
133 | class _OriginalSizedImage extends StatelessWidget {
134 | const _OriginalSizedImage({super.key});
135 |
136 | @override
137 | Widget build(BuildContext context) {
138 | RestorationManager;
139 | RestorationScope;
140 | RestorationMixin;
141 | CircularNotchedRectangle;
142 | return Image.asset(
143 | "assets/6392956.jpg",
144 | height: 100,
145 | width: 300,
146 | );
147 | }
148 | }
149 |
150 | class _CacheHeightImage extends StatelessWidget {
151 | final double height;
152 | const _CacheHeightImage(this.height, {super.key});
153 |
154 | @override
155 | Widget build(BuildContext context) {
156 | return Image.asset(
157 | "assets/6392956.jpg",
158 | height: 100,
159 | width: 300,
160 | cacheHeight: (height * MediaQuery.of(context).devicePixelRatio).toInt(),
161 | );
162 | }
163 | }
164 |
165 | class SvgTintExample extends StatelessWidget {
166 | const SvgTintExample({super.key});
167 |
168 | @override
169 | Widget build(BuildContext context) {
170 | return SvgPicture.network("https://upload.wikimedia.org/wikipedia/commons/thumb/3/30/Vector-based_example.svg/800px-Vector-based_example.svg", color: Colors.red,);
171 | }
172 | }
--------------------------------------------------------------------------------
/lib/8_shapes/shapes_example.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 | import 'dart:math' as math;
3 |
4 | import 'ticket_item.dart';
5 |
6 | class ShapesExample extends StatefulWidget {
7 | const ShapesExample({super.key});
8 |
9 | @override
10 | State createState() => _ShapesExampleState();
11 | }
12 |
13 | class _ShapesExampleState extends State {
14 | final dateIndicatorKey = GlobalKey();
15 |
16 | @override
17 | Widget build(BuildContext context) {
18 | return Scaffold(
19 | backgroundColor: Colors.white,
20 | appBar: AppBar(
21 | title: Text("Notches example"),
22 | ),
23 | body: Padding(
24 | padding: const EdgeInsets.all(20),
25 | child: Column(
26 | crossAxisAlignment: CrossAxisAlignment.center,
27 | children: [
28 | _item1(),
29 | SizedBox(height: 20),
30 |
31 | _item2(),
32 | // _item3(),
33 | // _item4(),
34 | SizedBox(height: 20),
35 | // _item5(),
36 | // _item6(),
37 | SizedBox(height: 20),
38 |
39 | // _item7(),
40 | // _item8(),
41 | ],
42 | ),
43 | ),
44 | floatingActionButton: Container(
45 | height: 50,
46 | width: 150,
47 | color: Colors.red,
48 | ),
49 | floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
50 | bottomNavigationBar: BottomAppBar(
51 | color: Colors.deepPurple,
52 | notchMargin: 10,
53 | shape: AutomaticNotchedShape(
54 | RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
55 | BeveledRectangleBorder(borderRadius: BorderRadius.circular(15)),
56 | ),
57 | child: Row(
58 | children: [Text('dsfdsfdsf')],
59 | ),
60 | ),
61 | );
62 | }
63 |
64 | Widget _item1() {
65 | return DecoratedBox(
66 | decoration: ShapeDecoration(
67 | color: Color(0xFFd6f5ff),
68 | shape: BeveledRectangleBorder(borderRadius: BorderRadius.circular(20))
69 | .lerpTo(
70 | BeveledRectangleBorder(borderRadius: BorderRadius.circular(1)),
71 | 0.4)!,
72 | ),
73 | child: const SizedBox(height: 200, width: 200),
74 | );
75 | }
76 |
77 | Widget _item2() {
78 | return DecoratedBox(
79 | decoration: BoxDecoration(
80 | borderRadius: BorderRadius.circular(10),
81 | shape: BoxShape.rectangle,
82 | color: Color(0xFFd6f5ff),
83 | ),
84 | child: const SizedBox(height: 200, width: 200),
85 | );
86 | }
87 |
88 | Widget _item3() {
89 | return DecoratedBox(
90 | decoration: ShapeDecoration(
91 | shape: StarBorder(),
92 | color: Colors.amber,
93 | ),
94 | child: const SizedBox(height: 100, width: 100),
95 | );
96 | }
97 |
98 | Widget _item4() {
99 | return MessageBubble(text: "Sample message text");
100 | }
101 |
102 | Widget _item5() {
103 | return DecoratedBox(
104 | decoration: ShapeDecoration(
105 | shape: MessageShapeBorder(
106 | borderRadius: 50,
107 | side: BorderSide(width: 0, color: Color(0xFF7ADEFF))),
108 | color: Color(0xFF7ADEFF),
109 | ),
110 | child: SizedBox(width: 500, height: 200),
111 | );
112 | }
113 |
114 | Widget _item7() {
115 | return ClipPath(
116 | clipper: const ShapeBorderClipper(
117 | shape: MessageShapeBorder(),
118 | ),
119 | child: Image.asset(
120 | "assets/6392956.jpg",
121 | height: 200,
122 | width: 300,
123 | fit: BoxFit.cover,
124 | cacheHeight: (300 * MediaQuery.of(context).devicePixelRatio).toInt(),
125 | ),
126 | );
127 | }
128 |
129 | Widget _item8() {
130 | return TicketItem(
131 | topChild: Padding(
132 | padding: EdgeInsets.all(16),
133 | child: Column(
134 | children: [
135 | Text("Top child"),
136 | ],
137 | ),
138 | ),
139 | bottomChild: ShaderMask(
140 | blendMode: BlendMode.srcATop,
141 | shaderCallback: (rectangle) => LinearGradient(
142 | begin: Alignment.topCenter,
143 | stops: [0, 1],
144 | colors: [Color(0xFFd6f5ff), Color(0x00d6f5ff)],
145 | end: Alignment.bottomCenter,
146 | ).createShader(rectangle),
147 | child: Image.asset(
148 | "assets/6392956.jpg",
149 | height: 200,
150 | width: 300,
151 | fit: BoxFit.cover,
152 | cacheHeight: (300 * MediaQuery.of(context).devicePixelRatio).toInt(),
153 | ),
154 | ),
155 | );
156 | }
157 | }
158 |
159 | class MessageBubble extends StatefulWidget {
160 | final String text;
161 | const MessageBubble({super.key, required this.text});
162 |
163 | @override
164 | State createState() => _MessageBubbleState();
165 | }
166 |
167 | class _MessageBubbleState extends State
168 | with SingleTickerProviderStateMixin {
169 | var isPressed = false;
170 |
171 | late Animation animation;
172 | late Tween tween;
173 | late AnimationController controller;
174 |
175 | @override
176 | void initState() {
177 | super.initState();
178 | controller =
179 | AnimationController(duration: kThemeAnimationDuration, vsync: this);
180 | tween = Tween(begin: 2.5, end: 5.0);
181 | animation = tween.animate(controller);
182 | }
183 |
184 | @override
185 | Widget build(BuildContext context) {
186 | return GestureDetector(
187 | onTapDown: (details) => setState(() {
188 | isPressed = true;
189 | controller.forward();
190 | }),
191 | onTapUp: (details) => setState(() {
192 | isPressed = false;
193 | controller.reverse();
194 | }),
195 | child: AnimatedBuilder(
196 | animation: animation,
197 | builder: (context, _) {
198 | return DecoratedBox(
199 | decoration: ShapeDecoration(
200 | shape: MessageShapeBorder(
201 | side: BorderSide(
202 | color: Color(0xFF7ADEFF), width: animation.value + 2),
203 | weight: animation.value,
204 | borderRadius: 30,
205 | ),
206 | color: const Color(0xFFd6f5ff),
207 | ),
208 | child: Padding(
209 | padding: EdgeInsets.all(20).copyWith(left: 30),
210 | child: Text(widget.text),
211 | ),
212 | );
213 | }),
214 | );
215 | }
216 | }
217 |
218 | class MessageShapeBorder extends OutlinedBorder {
219 | final double borderRadius;
220 | final double weight;
221 | // final Color fillColor;
222 |
223 | const MessageShapeBorder(
224 | {super.side,
225 | this.borderRadius = 50,
226 | /*required this.fillColor,*/ this.weight = 2.5});
227 |
228 | @override
229 | Path getInnerPath(Rect rect, {TextDirection? textDirection}) {
230 | final strokeWidth = side.width;
231 |
232 | final double left = rect.left + strokeWidth;
233 | final double right = rect.right - strokeWidth;
234 | final double top = rect.top + strokeWidth;
235 | final double bottom = rect.bottom - strokeWidth;
236 |
237 | final radius = math.max(0, borderRadius - 10);
238 | final offset = 10;
239 |
240 | return Path()
241 | ..moveTo(left + offset + radius, bottom)
242 | ..conicTo(
243 | left + offset, bottom, left + offset, bottom - 2 * radius, weight)
244 | ..lineTo(left + offset, top + radius)
245 | ..conicTo(left + offset, top, left + offset + radius, top, weight)
246 | ..lineTo(right - radius, top)
247 | ..conicTo(right, top, right, top + radius, weight)
248 | ..lineTo(right, bottom - radius)
249 | ..conicTo(right, bottom, right - radius, bottom, weight)
250 | ..close();
251 | }
252 |
253 | @override
254 | Path getOuterPath(Rect rect, {TextDirection? textDirection}) {
255 | final double left = rect.left;
256 | final double right = rect.right;
257 | final double top = rect.top;
258 | final double bottom = rect.bottom;
259 |
260 | final radius = borderRadius;
261 | final offset = 10;
262 |
263 | return Path()
264 | ..moveTo(left, bottom)
265 | ..conicTo(left + offset, bottom - offset, left + offset,
266 | bottom - 2 * radius, weight)
267 | ..lineTo(left + offset, top + radius)
268 | ..conicTo(left + offset, top, left + offset + radius, top, weight)
269 | ..lineTo(right - radius, top)
270 | ..conicTo(right, top, right, top + radius, weight)
271 | ..lineTo(right, bottom - radius)
272 | ..conicTo(right, bottom, right - radius, bottom, weight)
273 | ..close();
274 | }
275 |
276 | @override
277 | void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) {
278 | canvas.drawPath(getInnerPath(rect), Paint()..color = side.color);
279 | }
280 |
281 | @override
282 | ShapeBorder scale(double t) {
283 | return this; //
284 | }
285 |
286 | @override
287 | OutlinedBorder copyWith({BorderSide? side}) {
288 | return this; //
289 | }
290 | }
291 |
--------------------------------------------------------------------------------
/lib/8_shapes/ticket_item.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 |
3 | class TicketItem extends StatefulWidget {
4 | final Widget topChild;
5 | final Widget bottomChild;
6 |
7 | const TicketItem({super.key, required this.topChild, required this.bottomChild});
8 |
9 | @override
10 | State createState() => _TicketItemState();
11 | }
12 |
13 | class _TicketItemState extends State {
14 | final notchKey = GlobalKey();
15 |
16 | @override
17 | Widget build(BuildContext context) {
18 | return ClipPath(
19 | clipper: _TicketClipper(
20 | notchBox: notchKey.currentContext?.findRenderObject() as RenderBox,
21 | ancestorBox: context.findRenderObject() as RenderBox,
22 | ),
23 | child: ColoredBox(
24 | color: Color(0xFFd6f5ff),
25 | child: Column(
26 | children: [
27 | widget.topChild,
28 | SizedBox(key: notchKey, height: 20),
29 | widget.bottomChild,
30 | ],
31 | ),
32 | ),
33 | );
34 | }
35 | }
36 |
37 | class _TicketClipper extends CustomClipper {
38 | final RenderBox notchBox;
39 | final RenderBox ancestorBox;
40 |
41 | _TicketClipper({required this.notchBox, required this.ancestorBox});
42 |
43 | @override
44 | Path getClip(Size size) {
45 | final widgetRect = RRect.fromRectAndRadius(
46 | Rect.fromPoints(Offset.zero, Offset(size.width, size.height)),
47 | const Radius.circular(10),
48 | );
49 |
50 | final notch = notchBox.localToGlobal(Offset.zero, ancestor: ancestorBox);
51 |
52 | return Path.combine(
53 | PathOperation.difference,
54 | Path()..addRRect(widgetRect),
55 | Path()
56 | ..addOval(Rect.fromCenter(
57 | center: Offset(0, notch.dy + 10), width: 20, height: 20))
58 | ..addOval(Rect.fromCenter(
59 | center: Offset(size.width, notch.dy + 10), width: 20, height: 20)),
60 | );
61 | }
62 |
63 | @override
64 | bool shouldReclip(covariant CustomClipper oldClipper) {
65 | return true;
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/lib/9_layers/layers_example.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 |
3 | class LayersExample extends StatelessWidget {
4 | const LayersExample({super.key});
5 |
6 | @override
7 | Widget build(BuildContext context) {
8 | return _RepaintBoundaryExample();
9 |
10 | return Scaffold(
11 | appBar: AppBar(title: Text("Layers example")),
12 | body: Column(children: [
13 |
14 | RepaintBoundary(
15 | child: CircularProgressIndicator()
16 | ),
17 |
18 | // ColorFiltered(
19 | // colorFilter: ColorFilter.mode(Colors.red, BlendMode.difference),
20 | // child: Opacity(
21 | // opacity: 0.9,
22 | // child: Image.asset(
23 | // "assets/6392956.jpg",
24 | // height: 100,
25 | // width: 300,
26 | // cacheHeight:
27 | // (300 * MediaQuery.of(context).devicePixelRatio).toInt(),
28 | // ),
29 | // ),
30 | // ),
31 | // ColorFiltered(
32 | // colorFilter: ColorFilter.mode(Colors.red, BlendMode.difference),
33 | // child: Image.asset(
34 | // "assets/6392956.jpg",
35 | // height: 100,
36 | // width: 300,
37 | // cacheHeight:
38 | // (300 * MediaQuery.of(context).devicePixelRatio).toInt(),
39 | // ),
40 | // )
41 | ]),
42 |
43 | );
44 | // RepaintBoundary(child: Container());
45 | // RenderRepaintBoundary.debugAsymmetricPaintCount
46 | // RenderBox.;
47 | }
48 | }
49 |
50 | class _RepaintBoundaryExample extends StatelessWidget {
51 | const _RepaintBoundaryExample({super.key});
52 |
53 | @override
54 | Widget build(BuildContext context) {
55 | // debugDumpLayerTree();
56 | // debugDumpRenderTree();
57 | return Scaffold(
58 | appBar: AppBar(title: Text("Layers example")),
59 | body: Column(children: [
60 | Center(
61 | child: Padding(
62 | padding: const EdgeInsets.all(20),
63 | child: RepaintBoundary(
64 | child: CircularProgressIndicator()
65 | ),
66 | ),
67 | ),
68 | Text('Outer widget')
69 | ]),
70 | );
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/linux/.gitignore:
--------------------------------------------------------------------------------
1 | flutter/ephemeral
2 |
--------------------------------------------------------------------------------
/linux/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | # Project-level configuration.
2 | cmake_minimum_required(VERSION 3.10)
3 | project(runner LANGUAGES CXX)
4 |
5 | # The name of the executable created for the application. Change this to change
6 | # the on-disk name of your application.
7 | set(BINARY_NAME "flutter_ui_examples")
8 | # The unique GTK application identifier for this application. See:
9 | # https://wiki.gnome.org/HowDoI/ChooseApplicationID
10 | set(APPLICATION_ID "com.example.flutter_ui_examples")
11 |
12 | # Explicitly opt in to modern CMake behaviors to avoid warnings with recent
13 | # versions of CMake.
14 | cmake_policy(SET CMP0063 NEW)
15 |
16 | # Load bundled libraries from the lib/ directory relative to the binary.
17 | set(CMAKE_INSTALL_RPATH "$ORIGIN/lib")
18 |
19 | # Root filesystem for cross-building.
20 | if(FLUTTER_TARGET_PLATFORM_SYSROOT)
21 | set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT})
22 | set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT})
23 | set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
24 | set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
25 | set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
26 | set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
27 | endif()
28 |
29 | # Define build configuration options.
30 | if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
31 | set(CMAKE_BUILD_TYPE "Debug" CACHE
32 | STRING "Flutter build mode" FORCE)
33 | set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
34 | "Debug" "Profile" "Release")
35 | endif()
36 |
37 | # Compilation settings that should be applied to most targets.
38 | #
39 | # Be cautious about adding new options here, as plugins use this function by
40 | # default. In most cases, you should add new options to specific targets instead
41 | # of modifying this function.
42 | function(APPLY_STANDARD_SETTINGS TARGET)
43 | target_compile_features(${TARGET} PUBLIC cxx_std_14)
44 | target_compile_options(${TARGET} PRIVATE -Wall -Werror)
45 | target_compile_options(${TARGET} PRIVATE "$<$>:-O3>")
46 | target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>")
47 | endfunction()
48 |
49 | # Flutter library and tool build rules.
50 | set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter")
51 | add_subdirectory(${FLUTTER_MANAGED_DIR})
52 |
53 | # System-level dependencies.
54 | find_package(PkgConfig REQUIRED)
55 | pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
56 |
57 | add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}")
58 |
59 | # Define the application target. To change its name, change BINARY_NAME above,
60 | # not the value here, or `flutter run` will no longer work.
61 | #
62 | # Any new source files that you add to the application should be added here.
63 | add_executable(${BINARY_NAME}
64 | "main.cc"
65 | "my_application.cc"
66 | "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc"
67 | )
68 |
69 | # Apply the standard set of build settings. This can be removed for applications
70 | # that need different build settings.
71 | apply_standard_settings(${BINARY_NAME})
72 |
73 | # Add dependency libraries. Add any application-specific dependencies here.
74 | target_link_libraries(${BINARY_NAME} PRIVATE flutter)
75 | target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK)
76 |
77 | # Run the Flutter tool portions of the build. This must not be removed.
78 | add_dependencies(${BINARY_NAME} flutter_assemble)
79 |
80 | # Only the install-generated bundle's copy of the executable will launch
81 | # correctly, since the resources must in the right relative locations. To avoid
82 | # people trying to run the unbundled copy, put it in a subdirectory instead of
83 | # the default top-level location.
84 | set_target_properties(${BINARY_NAME}
85 | PROPERTIES
86 | RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run"
87 | )
88 |
89 |
90 | # Generated plugin build rules, which manage building the plugins and adding
91 | # them to the application.
92 | include(flutter/generated_plugins.cmake)
93 |
94 |
95 | # === Installation ===
96 | # By default, "installing" just makes a relocatable bundle in the build
97 | # directory.
98 | set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle")
99 | if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
100 | set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE)
101 | endif()
102 |
103 | # Start with a clean build bundle directory every time.
104 | install(CODE "
105 | file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\")
106 | " COMPONENT Runtime)
107 |
108 | set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data")
109 | set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib")
110 |
111 | install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}"
112 | COMPONENT Runtime)
113 |
114 | install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
115 | COMPONENT Runtime)
116 |
117 | install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
118 | COMPONENT Runtime)
119 |
120 | foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES})
121 | install(FILES "${bundled_library}"
122 | DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
123 | COMPONENT Runtime)
124 | endforeach(bundled_library)
125 |
126 | # Copy the native assets provided by the build.dart from all packages.
127 | set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/")
128 | install(DIRECTORY "${NATIVE_ASSETS_DIR}"
129 | DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
130 | COMPONENT Runtime)
131 |
132 | # Fully re-copy the assets directory on each build to avoid having stale files
133 | # from a previous install.
134 | set(FLUTTER_ASSET_DIR_NAME "flutter_assets")
135 | install(CODE "
136 | file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\")
137 | " COMPONENT Runtime)
138 | install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}"
139 | DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime)
140 |
141 | # Install the AOT library on non-Debug builds only.
142 | if(NOT CMAKE_BUILD_TYPE MATCHES "Debug")
143 | install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
144 | COMPONENT Runtime)
145 | endif()
146 |
--------------------------------------------------------------------------------
/linux/flutter/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | # This file controls Flutter-level build steps. It should not be edited.
2 | cmake_minimum_required(VERSION 3.10)
3 |
4 | set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral")
5 |
6 | # Configuration provided via flutter tool.
7 | include(${EPHEMERAL_DIR}/generated_config.cmake)
8 |
9 | # TODO: Move the rest of this into files in ephemeral. See
10 | # https://github.com/flutter/flutter/issues/57146.
11 |
12 | # Serves the same purpose as list(TRANSFORM ... PREPEND ...),
13 | # which isn't available in 3.10.
14 | function(list_prepend LIST_NAME PREFIX)
15 | set(NEW_LIST "")
16 | foreach(element ${${LIST_NAME}})
17 | list(APPEND NEW_LIST "${PREFIX}${element}")
18 | endforeach(element)
19 | set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE)
20 | endfunction()
21 |
22 | # === Flutter Library ===
23 | # System-level dependencies.
24 | find_package(PkgConfig REQUIRED)
25 | pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
26 | pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0)
27 | pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0)
28 |
29 | set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so")
30 |
31 | # Published to parent scope for install step.
32 | set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE)
33 | set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE)
34 | set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE)
35 | set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE)
36 |
37 | list(APPEND FLUTTER_LIBRARY_HEADERS
38 | "fl_basic_message_channel.h"
39 | "fl_binary_codec.h"
40 | "fl_binary_messenger.h"
41 | "fl_dart_project.h"
42 | "fl_engine.h"
43 | "fl_json_message_codec.h"
44 | "fl_json_method_codec.h"
45 | "fl_message_codec.h"
46 | "fl_method_call.h"
47 | "fl_method_channel.h"
48 | "fl_method_codec.h"
49 | "fl_method_response.h"
50 | "fl_plugin_registrar.h"
51 | "fl_plugin_registry.h"
52 | "fl_standard_message_codec.h"
53 | "fl_standard_method_codec.h"
54 | "fl_string_codec.h"
55 | "fl_value.h"
56 | "fl_view.h"
57 | "flutter_linux.h"
58 | )
59 | list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/")
60 | add_library(flutter INTERFACE)
61 | target_include_directories(flutter INTERFACE
62 | "${EPHEMERAL_DIR}"
63 | )
64 | target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}")
65 | target_link_libraries(flutter INTERFACE
66 | PkgConfig::GTK
67 | PkgConfig::GLIB
68 | PkgConfig::GIO
69 | )
70 | add_dependencies(flutter flutter_assemble)
71 |
72 | # === Flutter tool backend ===
73 | # _phony_ is a non-existent file to force this command to run every time,
74 | # since currently there's no way to get a full input/output list from the
75 | # flutter tool.
76 | add_custom_command(
77 | OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS}
78 | ${CMAKE_CURRENT_BINARY_DIR}/_phony_
79 | COMMAND ${CMAKE_COMMAND} -E env
80 | ${FLUTTER_TOOL_ENVIRONMENT}
81 | "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh"
82 | ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE}
83 | VERBATIM
84 | )
85 | add_custom_target(flutter_assemble DEPENDS
86 | "${FLUTTER_LIBRARY}"
87 | ${FLUTTER_LIBRARY_HEADERS}
88 | )
89 |
--------------------------------------------------------------------------------
/linux/flutter/generated_plugin_registrant.cc:
--------------------------------------------------------------------------------
1 | //
2 | // Generated file. Do not edit.
3 | //
4 |
5 | // clang-format off
6 |
7 | #include "generated_plugin_registrant.h"
8 |
9 |
10 | void fl_register_plugins(FlPluginRegistry* registry) {
11 | }
12 |
--------------------------------------------------------------------------------
/linux/flutter/generated_plugin_registrant.h:
--------------------------------------------------------------------------------
1 | //
2 | // Generated file. Do not edit.
3 | //
4 |
5 | // clang-format off
6 |
7 | #ifndef GENERATED_PLUGIN_REGISTRANT_
8 | #define GENERATED_PLUGIN_REGISTRANT_
9 |
10 | #include
11 |
12 | // Registers Flutter plugins.
13 | void fl_register_plugins(FlPluginRegistry* registry);
14 |
15 | #endif // GENERATED_PLUGIN_REGISTRANT_
16 |
--------------------------------------------------------------------------------
/linux/flutter/generated_plugins.cmake:
--------------------------------------------------------------------------------
1 | #
2 | # Generated file, do not edit.
3 | #
4 |
5 | list(APPEND FLUTTER_PLUGIN_LIST
6 | )
7 |
8 | list(APPEND FLUTTER_FFI_PLUGIN_LIST
9 | )
10 |
11 | set(PLUGIN_BUNDLED_LIBRARIES)
12 |
13 | foreach(plugin ${FLUTTER_PLUGIN_LIST})
14 | add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin})
15 | target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin)
16 | list(APPEND PLUGIN_BUNDLED_LIBRARIES $)
17 | list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries})
18 | endforeach(plugin)
19 |
20 | foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST})
21 | add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin})
22 | list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries})
23 | endforeach(ffi_plugin)
24 |
--------------------------------------------------------------------------------
/linux/main.cc:
--------------------------------------------------------------------------------
1 | #include "my_application.h"
2 |
3 | int main(int argc, char** argv) {
4 | g_autoptr(MyApplication) app = my_application_new();
5 | return g_application_run(G_APPLICATION(app), argc, argv);
6 | }
7 |
--------------------------------------------------------------------------------
/linux/my_application.cc:
--------------------------------------------------------------------------------
1 | #include "my_application.h"
2 |
3 | #include
4 | #ifdef GDK_WINDOWING_X11
5 | #include
6 | #endif
7 |
8 | #include "flutter/generated_plugin_registrant.h"
9 |
10 | struct _MyApplication {
11 | GtkApplication parent_instance;
12 | char** dart_entrypoint_arguments;
13 | };
14 |
15 | G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION)
16 |
17 | // Implements GApplication::activate.
18 | static void my_application_activate(GApplication* application) {
19 | MyApplication* self = MY_APPLICATION(application);
20 | GtkWindow* window =
21 | GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application)));
22 |
23 | // Use a header bar when running in GNOME as this is the common style used
24 | // by applications and is the setup most users will be using (e.g. Ubuntu
25 | // desktop).
26 | // If running on X and not using GNOME then just use a traditional title bar
27 | // in case the window manager does more exotic layout, e.g. tiling.
28 | // If running on Wayland assume the header bar will work (may need changing
29 | // if future cases occur).
30 | gboolean use_header_bar = TRUE;
31 | #ifdef GDK_WINDOWING_X11
32 | GdkScreen* screen = gtk_window_get_screen(window);
33 | if (GDK_IS_X11_SCREEN(screen)) {
34 | const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen);
35 | if (g_strcmp0(wm_name, "GNOME Shell") != 0) {
36 | use_header_bar = FALSE;
37 | }
38 | }
39 | #endif
40 | if (use_header_bar) {
41 | GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new());
42 | gtk_widget_show(GTK_WIDGET(header_bar));
43 | gtk_header_bar_set_title(header_bar, "flutter_ui_examples");
44 | gtk_header_bar_set_show_close_button(header_bar, TRUE);
45 | gtk_window_set_titlebar(window, GTK_WIDGET(header_bar));
46 | } else {
47 | gtk_window_set_title(window, "flutter_ui_examples");
48 | }
49 |
50 | gtk_window_set_default_size(window, 1280, 720);
51 | gtk_widget_show(GTK_WIDGET(window));
52 |
53 | g_autoptr(FlDartProject) project = fl_dart_project_new();
54 | fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments);
55 |
56 | FlView* view = fl_view_new(project);
57 | gtk_widget_show(GTK_WIDGET(view));
58 | gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view));
59 |
60 | fl_register_plugins(FL_PLUGIN_REGISTRY(view));
61 |
62 | gtk_widget_grab_focus(GTK_WIDGET(view));
63 | }
64 |
65 | // Implements GApplication::local_command_line.
66 | static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) {
67 | MyApplication* self = MY_APPLICATION(application);
68 | // Strip out the first argument as it is the binary name.
69 | self->dart_entrypoint_arguments = g_strdupv(*arguments + 1);
70 |
71 | g_autoptr(GError) error = nullptr;
72 | if (!g_application_register(application, nullptr, &error)) {
73 | g_warning("Failed to register: %s", error->message);
74 | *exit_status = 1;
75 | return TRUE;
76 | }
77 |
78 | g_application_activate(application);
79 | *exit_status = 0;
80 |
81 | return TRUE;
82 | }
83 |
84 | // Implements GObject::dispose.
85 | static void my_application_dispose(GObject* object) {
86 | MyApplication* self = MY_APPLICATION(object);
87 | g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev);
88 | G_OBJECT_CLASS(my_application_parent_class)->dispose(object);
89 | }
90 |
91 | static void my_application_class_init(MyApplicationClass* klass) {
92 | G_APPLICATION_CLASS(klass)->activate = my_application_activate;
93 | G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line;
94 | G_OBJECT_CLASS(klass)->dispose = my_application_dispose;
95 | }
96 |
97 | static void my_application_init(MyApplication* self) {}
98 |
99 | MyApplication* my_application_new() {
100 | return MY_APPLICATION(g_object_new(my_application_get_type(),
101 | "application-id", APPLICATION_ID,
102 | "flags", G_APPLICATION_NON_UNIQUE,
103 | nullptr));
104 | }
105 |
--------------------------------------------------------------------------------
/linux/my_application.h:
--------------------------------------------------------------------------------
1 | #ifndef FLUTTER_MY_APPLICATION_H_
2 | #define FLUTTER_MY_APPLICATION_H_
3 |
4 | #include
5 |
6 | G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION,
7 | GtkApplication)
8 |
9 | /**
10 | * my_application_new:
11 | *
12 | * Creates a new Flutter-based application.
13 | *
14 | * Returns: a new #MyApplication.
15 | */
16 | MyApplication* my_application_new();
17 |
18 | #endif // FLUTTER_MY_APPLICATION_H_
19 |
--------------------------------------------------------------------------------
/macos/.gitignore:
--------------------------------------------------------------------------------
1 | # Flutter-related
2 | **/Flutter/ephemeral/
3 | **/Pods/
4 |
5 | # Xcode-related
6 | **/dgph
7 | **/xcuserdata/
8 |
--------------------------------------------------------------------------------
/macos/Flutter/Flutter-Debug.xcconfig:
--------------------------------------------------------------------------------
1 | #include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"
2 | #include "ephemeral/Flutter-Generated.xcconfig"
3 |
--------------------------------------------------------------------------------
/macos/Flutter/Flutter-Release.xcconfig:
--------------------------------------------------------------------------------
1 | #include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"
2 | #include "ephemeral/Flutter-Generated.xcconfig"
3 |
--------------------------------------------------------------------------------
/macos/Flutter/GeneratedPluginRegistrant.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Generated file. Do not edit.
3 | //
4 |
5 | import FlutterMacOS
6 | import Foundation
7 |
8 | import path_provider_foundation
9 |
10 | func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
11 | PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin"))
12 | }
13 |
--------------------------------------------------------------------------------
/macos/Podfile:
--------------------------------------------------------------------------------
1 | platform :osx, '10.14'
2 |
3 | # CocoaPods analytics sends network stats synchronously affecting flutter build latency.
4 | ENV['COCOAPODS_DISABLE_STATS'] = 'true'
5 |
6 | project 'Runner', {
7 | 'Debug' => :debug,
8 | 'Profile' => :release,
9 | 'Release' => :release,
10 | }
11 |
12 | def flutter_root
13 | generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'ephemeral', 'Flutter-Generated.xcconfig'), __FILE__)
14 | unless File.exist?(generated_xcode_build_settings_path)
15 | raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure \"flutter pub get\" is executed first"
16 | end
17 |
18 | File.foreach(generated_xcode_build_settings_path) do |line|
19 | matches = line.match(/FLUTTER_ROOT\=(.*)/)
20 | return matches[1].strip if matches
21 | end
22 | raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Flutter-Generated.xcconfig, then run \"flutter pub get\""
23 | end
24 |
25 | require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)
26 |
27 | flutter_macos_podfile_setup
28 |
29 | target 'Runner' do
30 | use_frameworks!
31 | use_modular_headers!
32 |
33 | flutter_install_all_macos_pods File.dirname(File.realpath(__FILE__))
34 | target 'RunnerTests' do
35 | inherit! :search_paths
36 | end
37 | end
38 |
39 | post_install do |installer|
40 | installer.pods_project.targets.each do |target|
41 | flutter_additional_macos_build_settings(target)
42 | end
43 | end
44 |
--------------------------------------------------------------------------------
/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme:
--------------------------------------------------------------------------------
1 |
2 |
5 |
8 |
9 |
15 |
21 |
22 |
23 |
24 |
25 |
30 |
31 |
37 |
38 |
39 |
40 |
43 |
49 |
50 |
51 |
52 |
53 |
63 |
65 |
71 |
72 |
73 |
74 |
80 |
82 |
88 |
89 |
90 |
91 |
93 |
94 |
97 |
98 |
99 |
--------------------------------------------------------------------------------
/macos/Runner.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/macos/Runner/AppDelegate.swift:
--------------------------------------------------------------------------------
1 | import Cocoa
2 | import FlutterMacOS
3 |
4 | @NSApplicationMain
5 | class AppDelegate: FlutterAppDelegate {
6 | override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
7 | return true
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "size" : "16x16",
5 | "idiom" : "mac",
6 | "filename" : "app_icon_16.png",
7 | "scale" : "1x"
8 | },
9 | {
10 | "size" : "16x16",
11 | "idiom" : "mac",
12 | "filename" : "app_icon_32.png",
13 | "scale" : "2x"
14 | },
15 | {
16 | "size" : "32x32",
17 | "idiom" : "mac",
18 | "filename" : "app_icon_32.png",
19 | "scale" : "1x"
20 | },
21 | {
22 | "size" : "32x32",
23 | "idiom" : "mac",
24 | "filename" : "app_icon_64.png",
25 | "scale" : "2x"
26 | },
27 | {
28 | "size" : "128x128",
29 | "idiom" : "mac",
30 | "filename" : "app_icon_128.png",
31 | "scale" : "1x"
32 | },
33 | {
34 | "size" : "128x128",
35 | "idiom" : "mac",
36 | "filename" : "app_icon_256.png",
37 | "scale" : "2x"
38 | },
39 | {
40 | "size" : "256x256",
41 | "idiom" : "mac",
42 | "filename" : "app_icon_256.png",
43 | "scale" : "1x"
44 | },
45 | {
46 | "size" : "256x256",
47 | "idiom" : "mac",
48 | "filename" : "app_icon_512.png",
49 | "scale" : "2x"
50 | },
51 | {
52 | "size" : "512x512",
53 | "idiom" : "mac",
54 | "filename" : "app_icon_512.png",
55 | "scale" : "1x"
56 | },
57 | {
58 | "size" : "512x512",
59 | "idiom" : "mac",
60 | "filename" : "app_icon_1024.png",
61 | "scale" : "2x"
62 | }
63 | ],
64 | "info" : {
65 | "version" : 1,
66 | "author" : "xcode"
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png
--------------------------------------------------------------------------------
/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png
--------------------------------------------------------------------------------
/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png
--------------------------------------------------------------------------------
/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png
--------------------------------------------------------------------------------
/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png
--------------------------------------------------------------------------------
/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png
--------------------------------------------------------------------------------
/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png
--------------------------------------------------------------------------------
/macos/Runner/Configs/AppInfo.xcconfig:
--------------------------------------------------------------------------------
1 | // Application-level settings for the Runner target.
2 | //
3 | // This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the
4 | // future. If not, the values below would default to using the project name when this becomes a
5 | // 'flutter create' template.
6 |
7 | // The application's name. By default this is also the title of the Flutter window.
8 | PRODUCT_NAME = flutter_ui_examples
9 |
10 | // The application's bundle identifier
11 | PRODUCT_BUNDLE_IDENTIFIER = com.example.flutterUiExamples
12 |
13 | // The copyright displayed in application information
14 | PRODUCT_COPYRIGHT = Copyright © 2024 com.example. All rights reserved.
15 |
--------------------------------------------------------------------------------
/macos/Runner/Configs/Debug.xcconfig:
--------------------------------------------------------------------------------
1 | #include "../../Flutter/Flutter-Debug.xcconfig"
2 | #include "Warnings.xcconfig"
3 |
--------------------------------------------------------------------------------
/macos/Runner/Configs/Release.xcconfig:
--------------------------------------------------------------------------------
1 | #include "../../Flutter/Flutter-Release.xcconfig"
2 | #include "Warnings.xcconfig"
3 |
--------------------------------------------------------------------------------
/macos/Runner/Configs/Warnings.xcconfig:
--------------------------------------------------------------------------------
1 | WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings
2 | GCC_WARN_UNDECLARED_SELECTOR = YES
3 | CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES
4 | CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE
5 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES
6 | CLANG_WARN_PRAGMA_PACK = YES
7 | CLANG_WARN_STRICT_PROTOTYPES = YES
8 | CLANG_WARN_COMMA = YES
9 | GCC_WARN_STRICT_SELECTOR_MATCH = YES
10 | CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES
11 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES
12 | GCC_WARN_SHADOW = YES
13 | CLANG_WARN_UNREACHABLE_CODE = YES
14 |
--------------------------------------------------------------------------------
/macos/Runner/DebugProfile.entitlements:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | com.apple.security.app-sandbox
6 |
7 | com.apple.security.cs.allow-jit
8 |
9 | com.apple.security.network.server
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/macos/Runner/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | $(DEVELOPMENT_LANGUAGE)
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIconFile
10 |
11 | CFBundleIdentifier
12 | $(PRODUCT_BUNDLE_IDENTIFIER)
13 | CFBundleInfoDictionaryVersion
14 | 6.0
15 | CFBundleName
16 | $(PRODUCT_NAME)
17 | CFBundlePackageType
18 | APPL
19 | CFBundleShortVersionString
20 | $(FLUTTER_BUILD_NAME)
21 | CFBundleVersion
22 | $(FLUTTER_BUILD_NUMBER)
23 | LSMinimumSystemVersion
24 | $(MACOSX_DEPLOYMENT_TARGET)
25 | NSHumanReadableCopyright
26 | $(PRODUCT_COPYRIGHT)
27 | NSMainNibFile
28 | MainMenu
29 | NSPrincipalClass
30 | NSApplication
31 |
32 |
33 |
--------------------------------------------------------------------------------
/macos/Runner/MainFlutterWindow.swift:
--------------------------------------------------------------------------------
1 | import Cocoa
2 | import FlutterMacOS
3 |
4 | class MainFlutterWindow: NSWindow {
5 | override func awakeFromNib() {
6 | let flutterViewController = FlutterViewController()
7 | let windowFrame = self.frame
8 | self.contentViewController = flutterViewController
9 | self.setFrame(windowFrame, display: true)
10 |
11 | RegisterGeneratedPlugins(registry: flutterViewController)
12 |
13 | super.awakeFromNib()
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/macos/Runner/Release.entitlements:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | com.apple.security.app-sandbox
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/macos/RunnerTests/RunnerTests.swift:
--------------------------------------------------------------------------------
1 | import FlutterMacOS
2 | import Cocoa
3 | import XCTest
4 |
5 | class RunnerTests: XCTestCase {
6 |
7 | func testExample() {
8 | // If you add code to the Runner application, consider adding tests here.
9 | // See https://developer.apple.com/documentation/xctest for more information about using XCTest.
10 | }
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/pubspec.yaml:
--------------------------------------------------------------------------------
1 | name: flutter_ui_examples
2 | description: "A new Flutter project."
3 | # The following line prevents the package from being accidentally published to
4 | # pub.dev using `flutter pub publish`. This is preferred for private packages.
5 | publish_to: 'none' # Remove this line if you wish to publish to pub.dev
6 |
7 | # The following defines the version and build number for your application.
8 | # A version number is three numbers separated by dots, like 1.2.43
9 | # followed by an optional build number separated by a +.
10 | # Both the version and the builder number may be overridden in flutter
11 | # build by specifying --build-name and --build-number, respectively.
12 | # In Android, build-name is used as versionName while build-number used as versionCode.
13 | # Read more about Android versioning at https://developer.android.com/studio/publish/versioning
14 | # In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
15 | # Read more about iOS versioning at
16 | # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
17 | # In Windows, build-name is used as the major, minor, and patch parts
18 | # of the product and file versions while build-number is used as the build suffix.
19 | version: 1.0.0+1
20 |
21 | environment:
22 | sdk: '>=3.2.3 <4.0.0'
23 |
24 | # Dependencies specify other packages that your package needs in order to work.
25 | # To automatically upgrade your package dependencies to the latest versions
26 | # consider running `flutter pub upgrade --major-versions`. Alternatively,
27 | # dependencies can be manually updated by changing the version numbers below to
28 | # the latest version available on pub.dev. To see which dependencies have newer
29 | # versions available, run `flutter pub outdated`.
30 | dependencies:
31 | flutter:
32 | sdk: flutter
33 | flutter_localizations:
34 | sdk: flutter
35 |
36 | cupertino_icons: ^1.0.2
37 | slang_flutter: 3.15.0
38 | intl: ^0.19.0
39 | google_fonts: ^6.2.1
40 | flutter_svg: 2.0.10+1
41 | deferred_indexed_stack: ^0.0.4
42 | styled_text: 9.0.0-beta-4
43 | i18n:
44 | path: i18n
45 |
46 |
47 | dev_dependencies:
48 | flutter_test:
49 | sdk: flutter
50 | flutter_driver:
51 | sdk: flutter
52 | integration_test:
53 | sdk: flutter
54 | flutter_lints: ^2.0.0
55 | slang: 3.15.0
56 |
57 | # For information on the generic Dart part of this file, see the
58 | # following page: https://dart.dev/tools/pub/pubspec
59 |
60 | # The following section is specific to Flutter packages.
61 | flutter:
62 |
63 | # The following line ensures that the Material Icons font is
64 | # included with your application, so that you can use the icons in
65 | # the material Icons class.
66 | uses-material-design: true
67 |
68 | # To add assets to your application, add an assets section, like this:
69 | assets:
70 | - assets/
71 | # - images/a_dot_ham.jpeg
72 |
73 | # An image asset can refer to one or more resolution-specific "variants", see
74 | # https://flutter.dev/assets-and-images/#resolution-aware
75 |
76 | # For details regarding adding assets from package dependencies, see
77 | # https://flutter.dev/assets-and-images/#from-packages
78 |
79 | # To add custom fonts to your application, add a fonts section here,
80 | # in this "flutter" section. Each entry in this list should have a
81 | # "family" key with the font family name, and a "fonts" key with a
82 | # list giving the asset and other descriptors for the font. For
83 | # example:
84 | # fonts:
85 | # - family: Schyler
86 | # fonts:
87 | # - asset: fonts/Schyler-Regular.ttf
88 | # - asset: fonts/Schyler-Italic.ttf
89 | # style: italic
90 | # - family: Trajan Pro
91 | # fonts:
92 | # - asset: fonts/TrajanPro.ttf
93 | # - asset: fonts/TrajanPro_Bold.ttf
94 | # weight: 700
95 | #
96 | # For details regarding fonts from package dependencies,
97 | # see https://flutter.dev/custom-fonts/#from-packages
98 |
--------------------------------------------------------------------------------
/slang.yaml:
--------------------------------------------------------------------------------
1 | null_safety: true
2 | base_locale: en
3 | fallback_strategy: fallback_strategy
4 | input_directory: i18n/lib
5 | input_file_pattern: .i18n.json
6 | output_directory: i18n/lib/
7 | output_file_name: strings.g.dart
8 | translate_var: t
9 | enum_name: AppLocale
10 | translation_class_visibility: public
11 | key_case: camel
12 | string_interpolation: dart
13 | flat_map: false
--------------------------------------------------------------------------------
/test_driver/perf_driver.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter_driver/flutter_driver.dart' as driver;
2 | import 'package:integration_test/integration_test_driver.dart';
3 |
4 | Future main() {
5 | Future writeTimeline(Map? data, String timelineName) async {
6 | if (data?[timelineName] != null) {
7 | final timeline = driver.Timeline.fromJson(
8 | data![timelineName] as Map,
9 | );
10 |
11 | // Convert the Timeline into a TimelineSummary that's easier to
12 | // read and understand.
13 | final summary = driver.TimelineSummary.summarize(timeline);
14 |
15 | // Then, write the entire timeline to disk in a json format.
16 | // This file can be opened in the Chrome browser's tracing tools
17 | // found by navigating to chrome://tracing.
18 | // Optionally, save the summary to disk by setting includeSummary
19 | // to true
20 | print("Saving ${timelineName}_${DateTime.now().millisecondsSinceEpoch}");
21 |
22 | await summary.writeTimelineToFile(
23 | '${timelineName}_${DateTime.now().millisecondsSinceEpoch}',
24 | pretty: true,
25 | includeSummary: true,
26 | );
27 | }
28 | }
29 |
30 | return integrationDriver(responseDataCallback: (data) async {
31 | await writeTimeline(data, 'scrolling_timeline_no_keys');
32 | await writeTimeline(data, 'scrolling_timeline_global_keys');
33 | await writeTimeline(data, 'scrolling_timeline_value_keys');
34 | await writeTimeline(data, 'scrolling_timeline_sliver');
35 | await writeTimeline(data, 'scrolling_timeline_slivers_prototype');
36 | await writeTimeline(data, 'scrolling_timeline_shrink_wrap_never_scrollable');
37 | await writeTimeline(data, 'scrolling_timeline_shrink_wrap');
38 | });
39 | }
40 |
--------------------------------------------------------------------------------
/web/favicon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/web/favicon.png
--------------------------------------------------------------------------------
/web/icons/Icon-192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/web/icons/Icon-192.png
--------------------------------------------------------------------------------
/web/icons/Icon-512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/web/icons/Icon-512.png
--------------------------------------------------------------------------------
/web/icons/Icon-maskable-192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/web/icons/Icon-maskable-192.png
--------------------------------------------------------------------------------
/web/icons/Icon-maskable-512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/web/icons/Icon-maskable-512.png
--------------------------------------------------------------------------------
/web/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 | flutter_ui_examples
33 |
34 |
35 |
39 |
40 |
41 |
42 |
43 |
58 |
59 |
60 |
--------------------------------------------------------------------------------
/web/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "flutter_ui_examples",
3 | "short_name": "flutter_ui_examples",
4 | "start_url": ".",
5 | "display": "standalone",
6 | "background_color": "#0175C2",
7 | "theme_color": "#0175C2",
8 | "description": "A new Flutter project.",
9 | "orientation": "portrait-primary",
10 | "prefer_related_applications": false,
11 | "icons": [
12 | {
13 | "src": "icons/Icon-192.png",
14 | "sizes": "192x192",
15 | "type": "image/png"
16 | },
17 | {
18 | "src": "icons/Icon-512.png",
19 | "sizes": "512x512",
20 | "type": "image/png"
21 | },
22 | {
23 | "src": "icons/Icon-maskable-192.png",
24 | "sizes": "192x192",
25 | "type": "image/png",
26 | "purpose": "maskable"
27 | },
28 | {
29 | "src": "icons/Icon-maskable-512.png",
30 | "sizes": "512x512",
31 | "type": "image/png",
32 | "purpose": "maskable"
33 | }
34 | ]
35 | }
36 |
--------------------------------------------------------------------------------
/windows/.gitignore:
--------------------------------------------------------------------------------
1 | flutter/ephemeral/
2 |
3 | # Visual Studio user-specific files.
4 | *.suo
5 | *.user
6 | *.userosscache
7 | *.sln.docstates
8 |
9 | # Visual Studio build-related files.
10 | x64/
11 | x86/
12 |
13 | # Visual Studio cache files
14 | # files ending in .cache can be ignored
15 | *.[Cc]ache
16 | # but keep track of directories ending in .cache
17 | !*.[Cc]ache/
18 |
--------------------------------------------------------------------------------
/windows/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | # Project-level configuration.
2 | cmake_minimum_required(VERSION 3.14)
3 | project(flutter_ui_examples LANGUAGES CXX)
4 |
5 | # The name of the executable created for the application. Change this to change
6 | # the on-disk name of your application.
7 | set(BINARY_NAME "flutter_ui_examples")
8 |
9 | # Explicitly opt in to modern CMake behaviors to avoid warnings with recent
10 | # versions of CMake.
11 | cmake_policy(VERSION 3.14...3.25)
12 |
13 | # Define build configuration option.
14 | get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
15 | if(IS_MULTICONFIG)
16 | set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release"
17 | CACHE STRING "" FORCE)
18 | else()
19 | if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
20 | set(CMAKE_BUILD_TYPE "Debug" CACHE
21 | STRING "Flutter build mode" FORCE)
22 | set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
23 | "Debug" "Profile" "Release")
24 | endif()
25 | endif()
26 | # Define settings for the Profile build mode.
27 | set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}")
28 | set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}")
29 | set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}")
30 | set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}")
31 |
32 | # Use Unicode for all projects.
33 | add_definitions(-DUNICODE -D_UNICODE)
34 |
35 | # Compilation settings that should be applied to most targets.
36 | #
37 | # Be cautious about adding new options here, as plugins use this function by
38 | # default. In most cases, you should add new options to specific targets instead
39 | # of modifying this function.
40 | function(APPLY_STANDARD_SETTINGS TARGET)
41 | target_compile_features(${TARGET} PUBLIC cxx_std_17)
42 | target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100")
43 | target_compile_options(${TARGET} PRIVATE /EHsc)
44 | target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0")
45 | target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>")
46 | endfunction()
47 |
48 | # Flutter library and tool build rules.
49 | set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter")
50 | add_subdirectory(${FLUTTER_MANAGED_DIR})
51 |
52 | # Application build; see runner/CMakeLists.txt.
53 | add_subdirectory("runner")
54 |
55 |
56 | # Generated plugin build rules, which manage building the plugins and adding
57 | # them to the application.
58 | include(flutter/generated_plugins.cmake)
59 |
60 |
61 | # === Installation ===
62 | # Support files are copied into place next to the executable, so that it can
63 | # run in place. This is done instead of making a separate bundle (as on Linux)
64 | # so that building and running from within Visual Studio will work.
65 | set(BUILD_BUNDLE_DIR "$")
66 | # Make the "install" step default, as it's required to run.
67 | set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1)
68 | if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
69 | set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE)
70 | endif()
71 |
72 | set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data")
73 | set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}")
74 |
75 | install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}"
76 | COMPONENT Runtime)
77 |
78 | install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
79 | COMPONENT Runtime)
80 |
81 | install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
82 | COMPONENT Runtime)
83 |
84 | if(PLUGIN_BUNDLED_LIBRARIES)
85 | install(FILES "${PLUGIN_BUNDLED_LIBRARIES}"
86 | DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
87 | COMPONENT Runtime)
88 | endif()
89 |
90 | # Copy the native assets provided by the build.dart from all packages.
91 | set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/")
92 | install(DIRECTORY "${NATIVE_ASSETS_DIR}"
93 | DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
94 | COMPONENT Runtime)
95 |
96 | # Fully re-copy the assets directory on each build to avoid having stale files
97 | # from a previous install.
98 | set(FLUTTER_ASSET_DIR_NAME "flutter_assets")
99 | install(CODE "
100 | file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\")
101 | " COMPONENT Runtime)
102 | install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}"
103 | DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime)
104 |
105 | # Install the AOT library on non-Debug builds only.
106 | install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
107 | CONFIGURATIONS Profile;Release
108 | COMPONENT Runtime)
109 |
--------------------------------------------------------------------------------
/windows/flutter/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | # This file controls Flutter-level build steps. It should not be edited.
2 | cmake_minimum_required(VERSION 3.14)
3 |
4 | set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral")
5 |
6 | # Configuration provided via flutter tool.
7 | include(${EPHEMERAL_DIR}/generated_config.cmake)
8 |
9 | # TODO: Move the rest of this into files in ephemeral. See
10 | # https://github.com/flutter/flutter/issues/57146.
11 | set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper")
12 |
13 | # Set fallback configurations for older versions of the flutter tool.
14 | if (NOT DEFINED FLUTTER_TARGET_PLATFORM)
15 | set(FLUTTER_TARGET_PLATFORM "windows-x64")
16 | endif()
17 |
18 | # === Flutter Library ===
19 | set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll")
20 |
21 | # Published to parent scope for install step.
22 | set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE)
23 | set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE)
24 | set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE)
25 | set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE)
26 |
27 | list(APPEND FLUTTER_LIBRARY_HEADERS
28 | "flutter_export.h"
29 | "flutter_windows.h"
30 | "flutter_messenger.h"
31 | "flutter_plugin_registrar.h"
32 | "flutter_texture_registrar.h"
33 | )
34 | list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/")
35 | add_library(flutter INTERFACE)
36 | target_include_directories(flutter INTERFACE
37 | "${EPHEMERAL_DIR}"
38 | )
39 | target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib")
40 | add_dependencies(flutter flutter_assemble)
41 |
42 | # === Wrapper ===
43 | list(APPEND CPP_WRAPPER_SOURCES_CORE
44 | "core_implementations.cc"
45 | "standard_codec.cc"
46 | )
47 | list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/")
48 | list(APPEND CPP_WRAPPER_SOURCES_PLUGIN
49 | "plugin_registrar.cc"
50 | )
51 | list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/")
52 | list(APPEND CPP_WRAPPER_SOURCES_APP
53 | "flutter_engine.cc"
54 | "flutter_view_controller.cc"
55 | )
56 | list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/")
57 |
58 | # Wrapper sources needed for a plugin.
59 | add_library(flutter_wrapper_plugin STATIC
60 | ${CPP_WRAPPER_SOURCES_CORE}
61 | ${CPP_WRAPPER_SOURCES_PLUGIN}
62 | )
63 | apply_standard_settings(flutter_wrapper_plugin)
64 | set_target_properties(flutter_wrapper_plugin PROPERTIES
65 | POSITION_INDEPENDENT_CODE ON)
66 | set_target_properties(flutter_wrapper_plugin PROPERTIES
67 | CXX_VISIBILITY_PRESET hidden)
68 | target_link_libraries(flutter_wrapper_plugin PUBLIC flutter)
69 | target_include_directories(flutter_wrapper_plugin PUBLIC
70 | "${WRAPPER_ROOT}/include"
71 | )
72 | add_dependencies(flutter_wrapper_plugin flutter_assemble)
73 |
74 | # Wrapper sources needed for the runner.
75 | add_library(flutter_wrapper_app STATIC
76 | ${CPP_WRAPPER_SOURCES_CORE}
77 | ${CPP_WRAPPER_SOURCES_APP}
78 | )
79 | apply_standard_settings(flutter_wrapper_app)
80 | target_link_libraries(flutter_wrapper_app PUBLIC flutter)
81 | target_include_directories(flutter_wrapper_app PUBLIC
82 | "${WRAPPER_ROOT}/include"
83 | )
84 | add_dependencies(flutter_wrapper_app flutter_assemble)
85 |
86 | # === Flutter tool backend ===
87 | # _phony_ is a non-existent file to force this command to run every time,
88 | # since currently there's no way to get a full input/output list from the
89 | # flutter tool.
90 | set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_")
91 | set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE)
92 | add_custom_command(
93 | OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS}
94 | ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN}
95 | ${CPP_WRAPPER_SOURCES_APP}
96 | ${PHONY_OUTPUT}
97 | COMMAND ${CMAKE_COMMAND} -E env
98 | ${FLUTTER_TOOL_ENVIRONMENT}
99 | "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat"
100 | ${FLUTTER_TARGET_PLATFORM} $
101 | VERBATIM
102 | )
103 | add_custom_target(flutter_assemble DEPENDS
104 | "${FLUTTER_LIBRARY}"
105 | ${FLUTTER_LIBRARY_HEADERS}
106 | ${CPP_WRAPPER_SOURCES_CORE}
107 | ${CPP_WRAPPER_SOURCES_PLUGIN}
108 | ${CPP_WRAPPER_SOURCES_APP}
109 | )
110 |
--------------------------------------------------------------------------------
/windows/flutter/generated_plugin_registrant.cc:
--------------------------------------------------------------------------------
1 | //
2 | // Generated file. Do not edit.
3 | //
4 |
5 | // clang-format off
6 |
7 | #include "generated_plugin_registrant.h"
8 |
9 |
10 | void RegisterPlugins(flutter::PluginRegistry* registry) {
11 | }
12 |
--------------------------------------------------------------------------------
/windows/flutter/generated_plugin_registrant.h:
--------------------------------------------------------------------------------
1 | //
2 | // Generated file. Do not edit.
3 | //
4 |
5 | // clang-format off
6 |
7 | #ifndef GENERATED_PLUGIN_REGISTRANT_
8 | #define GENERATED_PLUGIN_REGISTRANT_
9 |
10 | #include
11 |
12 | // Registers Flutter plugins.
13 | void RegisterPlugins(flutter::PluginRegistry* registry);
14 |
15 | #endif // GENERATED_PLUGIN_REGISTRANT_
16 |
--------------------------------------------------------------------------------
/windows/flutter/generated_plugins.cmake:
--------------------------------------------------------------------------------
1 | #
2 | # Generated file, do not edit.
3 | #
4 |
5 | list(APPEND FLUTTER_PLUGIN_LIST
6 | )
7 |
8 | list(APPEND FLUTTER_FFI_PLUGIN_LIST
9 | )
10 |
11 | set(PLUGIN_BUNDLED_LIBRARIES)
12 |
13 | foreach(plugin ${FLUTTER_PLUGIN_LIST})
14 | add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin})
15 | target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin)
16 | list(APPEND PLUGIN_BUNDLED_LIBRARIES $)
17 | list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries})
18 | endforeach(plugin)
19 |
20 | foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST})
21 | add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin})
22 | list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries})
23 | endforeach(ffi_plugin)
24 |
--------------------------------------------------------------------------------
/windows/runner/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | cmake_minimum_required(VERSION 3.14)
2 | project(runner LANGUAGES CXX)
3 |
4 | # Define the application target. To change its name, change BINARY_NAME in the
5 | # top-level CMakeLists.txt, not the value here, or `flutter run` will no longer
6 | # work.
7 | #
8 | # Any new source files that you add to the application should be added here.
9 | add_executable(${BINARY_NAME} WIN32
10 | "flutter_window.cpp"
11 | "main.cpp"
12 | "utils.cpp"
13 | "win32_window.cpp"
14 | "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc"
15 | "Runner.rc"
16 | "runner.exe.manifest"
17 | )
18 |
19 | # Apply the standard set of build settings. This can be removed for applications
20 | # that need different build settings.
21 | apply_standard_settings(${BINARY_NAME})
22 |
23 | # Add preprocessor definitions for the build version.
24 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"")
25 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}")
26 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}")
27 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}")
28 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}")
29 |
30 | # Disable Windows macros that collide with C++ standard library functions.
31 | target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX")
32 |
33 | # Add dependency libraries and include directories. Add any application-specific
34 | # dependencies here.
35 | target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app)
36 | target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib")
37 | target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}")
38 |
39 | # Run the Flutter tool portions of the build. This must not be removed.
40 | add_dependencies(${BINARY_NAME} flutter_assemble)
41 |
--------------------------------------------------------------------------------
/windows/runner/Runner.rc:
--------------------------------------------------------------------------------
1 | // Microsoft Visual C++ generated resource script.
2 | //
3 | #pragma code_page(65001)
4 | #include "resource.h"
5 |
6 | #define APSTUDIO_READONLY_SYMBOLS
7 | /////////////////////////////////////////////////////////////////////////////
8 | //
9 | // Generated from the TEXTINCLUDE 2 resource.
10 | //
11 | #include "winres.h"
12 |
13 | /////////////////////////////////////////////////////////////////////////////
14 | #undef APSTUDIO_READONLY_SYMBOLS
15 |
16 | /////////////////////////////////////////////////////////////////////////////
17 | // English (United States) resources
18 |
19 | #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
20 | LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
21 |
22 | #ifdef APSTUDIO_INVOKED
23 | /////////////////////////////////////////////////////////////////////////////
24 | //
25 | // TEXTINCLUDE
26 | //
27 |
28 | 1 TEXTINCLUDE
29 | BEGIN
30 | "resource.h\0"
31 | END
32 |
33 | 2 TEXTINCLUDE
34 | BEGIN
35 | "#include ""winres.h""\r\n"
36 | "\0"
37 | END
38 |
39 | 3 TEXTINCLUDE
40 | BEGIN
41 | "\r\n"
42 | "\0"
43 | END
44 |
45 | #endif // APSTUDIO_INVOKED
46 |
47 |
48 | /////////////////////////////////////////////////////////////////////////////
49 | //
50 | // Icon
51 | //
52 |
53 | // Icon with lowest ID value placed first to ensure application icon
54 | // remains consistent on all systems.
55 | IDI_APP_ICON ICON "resources\\app_icon.ico"
56 |
57 |
58 | /////////////////////////////////////////////////////////////////////////////
59 | //
60 | // Version
61 | //
62 |
63 | #if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD)
64 | #define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD
65 | #else
66 | #define VERSION_AS_NUMBER 1,0,0,0
67 | #endif
68 |
69 | #if defined(FLUTTER_VERSION)
70 | #define VERSION_AS_STRING FLUTTER_VERSION
71 | #else
72 | #define VERSION_AS_STRING "1.0.0"
73 | #endif
74 |
75 | VS_VERSION_INFO VERSIONINFO
76 | FILEVERSION VERSION_AS_NUMBER
77 | PRODUCTVERSION VERSION_AS_NUMBER
78 | FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
79 | #ifdef _DEBUG
80 | FILEFLAGS VS_FF_DEBUG
81 | #else
82 | FILEFLAGS 0x0L
83 | #endif
84 | FILEOS VOS__WINDOWS32
85 | FILETYPE VFT_APP
86 | FILESUBTYPE 0x0L
87 | BEGIN
88 | BLOCK "StringFileInfo"
89 | BEGIN
90 | BLOCK "040904e4"
91 | BEGIN
92 | VALUE "CompanyName", "com.example" "\0"
93 | VALUE "FileDescription", "flutter_ui_examples" "\0"
94 | VALUE "FileVersion", VERSION_AS_STRING "\0"
95 | VALUE "InternalName", "flutter_ui_examples" "\0"
96 | VALUE "LegalCopyright", "Copyright (C) 2024 com.example. All rights reserved." "\0"
97 | VALUE "OriginalFilename", "flutter_ui_examples.exe" "\0"
98 | VALUE "ProductName", "flutter_ui_examples" "\0"
99 | VALUE "ProductVersion", VERSION_AS_STRING "\0"
100 | END
101 | END
102 | BLOCK "VarFileInfo"
103 | BEGIN
104 | VALUE "Translation", 0x409, 1252
105 | END
106 | END
107 |
108 | #endif // English (United States) resources
109 | /////////////////////////////////////////////////////////////////////////////
110 |
111 |
112 |
113 | #ifndef APSTUDIO_INVOKED
114 | /////////////////////////////////////////////////////////////////////////////
115 | //
116 | // Generated from the TEXTINCLUDE 3 resource.
117 | //
118 |
119 |
120 | /////////////////////////////////////////////////////////////////////////////
121 | #endif // not APSTUDIO_INVOKED
122 |
--------------------------------------------------------------------------------
/windows/runner/flutter_window.cpp:
--------------------------------------------------------------------------------
1 | #include "flutter_window.h"
2 |
3 | #include
4 |
5 | #include "flutter/generated_plugin_registrant.h"
6 |
7 | FlutterWindow::FlutterWindow(const flutter::DartProject& project)
8 | : project_(project) {}
9 |
10 | FlutterWindow::~FlutterWindow() {}
11 |
12 | bool FlutterWindow::OnCreate() {
13 | if (!Win32Window::OnCreate()) {
14 | return false;
15 | }
16 |
17 | RECT frame = GetClientArea();
18 |
19 | // The size here must match the window dimensions to avoid unnecessary surface
20 | // creation / destruction in the startup path.
21 | flutter_controller_ = std::make_unique(
22 | frame.right - frame.left, frame.bottom - frame.top, project_);
23 | // Ensure that basic setup of the controller was successful.
24 | if (!flutter_controller_->engine() || !flutter_controller_->view()) {
25 | return false;
26 | }
27 | RegisterPlugins(flutter_controller_->engine());
28 | SetChildContent(flutter_controller_->view()->GetNativeWindow());
29 |
30 | flutter_controller_->engine()->SetNextFrameCallback([&]() {
31 | this->Show();
32 | });
33 |
34 | // Flutter can complete the first frame before the "show window" callback is
35 | // registered. The following call ensures a frame is pending to ensure the
36 | // window is shown. It is a no-op if the first frame hasn't completed yet.
37 | flutter_controller_->ForceRedraw();
38 |
39 | return true;
40 | }
41 |
42 | void FlutterWindow::OnDestroy() {
43 | if (flutter_controller_) {
44 | flutter_controller_ = nullptr;
45 | }
46 |
47 | Win32Window::OnDestroy();
48 | }
49 |
50 | LRESULT
51 | FlutterWindow::MessageHandler(HWND hwnd, UINT const message,
52 | WPARAM const wparam,
53 | LPARAM const lparam) noexcept {
54 | // Give Flutter, including plugins, an opportunity to handle window messages.
55 | if (flutter_controller_) {
56 | std::optional result =
57 | flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam,
58 | lparam);
59 | if (result) {
60 | return *result;
61 | }
62 | }
63 |
64 | switch (message) {
65 | case WM_FONTCHANGE:
66 | flutter_controller_->engine()->ReloadSystemFonts();
67 | break;
68 | }
69 |
70 | return Win32Window::MessageHandler(hwnd, message, wparam, lparam);
71 | }
72 |
--------------------------------------------------------------------------------
/windows/runner/flutter_window.h:
--------------------------------------------------------------------------------
1 | #ifndef RUNNER_FLUTTER_WINDOW_H_
2 | #define RUNNER_FLUTTER_WINDOW_H_
3 |
4 | #include
5 | #include
6 |
7 | #include
8 |
9 | #include "win32_window.h"
10 |
11 | // A window that does nothing but host a Flutter view.
12 | class FlutterWindow : public Win32Window {
13 | public:
14 | // Creates a new FlutterWindow hosting a Flutter view running |project|.
15 | explicit FlutterWindow(const flutter::DartProject& project);
16 | virtual ~FlutterWindow();
17 |
18 | protected:
19 | // Win32Window:
20 | bool OnCreate() override;
21 | void OnDestroy() override;
22 | LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam,
23 | LPARAM const lparam) noexcept override;
24 |
25 | private:
26 | // The project to run.
27 | flutter::DartProject project_;
28 |
29 | // The Flutter instance hosted by this window.
30 | std::unique_ptr flutter_controller_;
31 | };
32 |
33 | #endif // RUNNER_FLUTTER_WINDOW_H_
34 |
--------------------------------------------------------------------------------
/windows/runner/main.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | #include "flutter_window.h"
6 | #include "utils.h"
7 |
8 | int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
9 | _In_ wchar_t *command_line, _In_ int show_command) {
10 | // Attach to console when present (e.g., 'flutter run') or create a
11 | // new console when running with a debugger.
12 | if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
13 | CreateAndAttachConsole();
14 | }
15 |
16 | // Initialize COM, so that it is available for use in the library and/or
17 | // plugins.
18 | ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
19 |
20 | flutter::DartProject project(L"data");
21 |
22 | std::vector command_line_arguments =
23 | GetCommandLineArguments();
24 |
25 | project.set_dart_entrypoint_arguments(std::move(command_line_arguments));
26 |
27 | FlutterWindow window(project);
28 | Win32Window::Point origin(10, 10);
29 | Win32Window::Size size(1280, 720);
30 | if (!window.Create(L"flutter_ui_examples", origin, size)) {
31 | return EXIT_FAILURE;
32 | }
33 | window.SetQuitOnClose(true);
34 |
35 | ::MSG msg;
36 | while (::GetMessage(&msg, nullptr, 0, 0)) {
37 | ::TranslateMessage(&msg);
38 | ::DispatchMessage(&msg);
39 | }
40 |
41 | ::CoUninitialize();
42 | return EXIT_SUCCESS;
43 | }
44 |
--------------------------------------------------------------------------------
/windows/runner/resource.h:
--------------------------------------------------------------------------------
1 | //{{NO_DEPENDENCIES}}
2 | // Microsoft Visual C++ generated include file.
3 | // Used by Runner.rc
4 | //
5 | #define IDI_APP_ICON 101
6 |
7 | // Next default values for new objects
8 | //
9 | #ifdef APSTUDIO_INVOKED
10 | #ifndef APSTUDIO_READONLY_SYMBOLS
11 | #define _APS_NEXT_RESOURCE_VALUE 102
12 | #define _APS_NEXT_COMMAND_VALUE 40001
13 | #define _APS_NEXT_CONTROL_VALUE 1001
14 | #define _APS_NEXT_SYMED_VALUE 101
15 | #endif
16 | #endif
17 |
--------------------------------------------------------------------------------
/windows/runner/resources/app_icon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pomis/flutter_native_ui_examples/4cb5a1be0b3833d70de8ef8fa50fdc9e2656661c/windows/runner/resources/app_icon.ico
--------------------------------------------------------------------------------
/windows/runner/runner.exe.manifest:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | PerMonitorV2
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/windows/runner/utils.cpp:
--------------------------------------------------------------------------------
1 | #include "utils.h"
2 |
3 | #include
4 | #include
5 | #include
6 | #include
7 |
8 | #include
9 |
10 | void CreateAndAttachConsole() {
11 | if (::AllocConsole()) {
12 | FILE *unused;
13 | if (freopen_s(&unused, "CONOUT$", "w", stdout)) {
14 | _dup2(_fileno(stdout), 1);
15 | }
16 | if (freopen_s(&unused, "CONOUT$", "w", stderr)) {
17 | _dup2(_fileno(stdout), 2);
18 | }
19 | std::ios::sync_with_stdio();
20 | FlutterDesktopResyncOutputStreams();
21 | }
22 | }
23 |
24 | std::vector GetCommandLineArguments() {
25 | // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use.
26 | int argc;
27 | wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc);
28 | if (argv == nullptr) {
29 | return std::vector();
30 | }
31 |
32 | std::vector command_line_arguments;
33 |
34 | // Skip the first argument as it's the binary name.
35 | for (int i = 1; i < argc; i++) {
36 | command_line_arguments.push_back(Utf8FromUtf16(argv[i]));
37 | }
38 |
39 | ::LocalFree(argv);
40 |
41 | return command_line_arguments;
42 | }
43 |
44 | std::string Utf8FromUtf16(const wchar_t* utf16_string) {
45 | if (utf16_string == nullptr) {
46 | return std::string();
47 | }
48 | int target_length = ::WideCharToMultiByte(
49 | CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
50 | -1, nullptr, 0, nullptr, nullptr)
51 | -1; // remove the trailing null character
52 | int input_length = (int)wcslen(utf16_string);
53 | std::string utf8_string;
54 | if (target_length <= 0 || target_length > utf8_string.max_size()) {
55 | return utf8_string;
56 | }
57 | utf8_string.resize(target_length);
58 | int converted_length = ::WideCharToMultiByte(
59 | CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
60 | input_length, utf8_string.data(), target_length, nullptr, nullptr);
61 | if (converted_length == 0) {
62 | return std::string();
63 | }
64 | return utf8_string;
65 | }
66 |
--------------------------------------------------------------------------------
/windows/runner/utils.h:
--------------------------------------------------------------------------------
1 | #ifndef RUNNER_UTILS_H_
2 | #define RUNNER_UTILS_H_
3 |
4 | #include
5 | #include
6 |
7 | // Creates a console for the process, and redirects stdout and stderr to
8 | // it for both the runner and the Flutter library.
9 | void CreateAndAttachConsole();
10 |
11 | // Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string
12 | // encoded in UTF-8. Returns an empty std::string on failure.
13 | std::string Utf8FromUtf16(const wchar_t* utf16_string);
14 |
15 | // Gets the command line arguments passed in as a std::vector,
16 | // encoded in UTF-8. Returns an empty std::vector on failure.
17 | std::vector GetCommandLineArguments();
18 |
19 | #endif // RUNNER_UTILS_H_
20 |
--------------------------------------------------------------------------------
/windows/runner/win32_window.h:
--------------------------------------------------------------------------------
1 | #ifndef RUNNER_WIN32_WINDOW_H_
2 | #define RUNNER_WIN32_WINDOW_H_
3 |
4 | #include
5 |
6 | #include
7 | #include
8 | #include
9 |
10 | // A class abstraction for a high DPI-aware Win32 Window. Intended to be
11 | // inherited from by classes that wish to specialize with custom
12 | // rendering and input handling
13 | class Win32Window {
14 | public:
15 | struct Point {
16 | unsigned int x;
17 | unsigned int y;
18 | Point(unsigned int x, unsigned int y) : x(x), y(y) {}
19 | };
20 |
21 | struct Size {
22 | unsigned int width;
23 | unsigned int height;
24 | Size(unsigned int width, unsigned int height)
25 | : width(width), height(height) {}
26 | };
27 |
28 | Win32Window();
29 | virtual ~Win32Window();
30 |
31 | // Creates a win32 window with |title| that is positioned and sized using
32 | // |origin| and |size|. New windows are created on the default monitor. Window
33 | // sizes are specified to the OS in physical pixels, hence to ensure a
34 | // consistent size this function will scale the inputted width and height as
35 | // as appropriate for the default monitor. The window is invisible until
36 | // |Show| is called. Returns true if the window was created successfully.
37 | bool Create(const std::wstring& title, const Point& origin, const Size& size);
38 |
39 | // Show the current window. Returns true if the window was successfully shown.
40 | bool Show();
41 |
42 | // Release OS resources associated with window.
43 | void Destroy();
44 |
45 | // Inserts |content| into the window tree.
46 | void SetChildContent(HWND content);
47 |
48 | // Returns the backing Window handle to enable clients to set icon and other
49 | // window properties. Returns nullptr if the window has been destroyed.
50 | HWND GetHandle();
51 |
52 | // If true, closing this window will quit the application.
53 | void SetQuitOnClose(bool quit_on_close);
54 |
55 | // Return a RECT representing the bounds of the current client area.
56 | RECT GetClientArea();
57 |
58 | protected:
59 | // Processes and route salient window messages for mouse handling,
60 | // size change and DPI. Delegates handling of these to member overloads that
61 | // inheriting classes can handle.
62 | virtual LRESULT MessageHandler(HWND window,
63 | UINT const message,
64 | WPARAM const wparam,
65 | LPARAM const lparam) noexcept;
66 |
67 | // Called when CreateAndShow is called, allowing subclass window-related
68 | // setup. Subclasses should return false if setup fails.
69 | virtual bool OnCreate();
70 |
71 | // Called when Destroy is called.
72 | virtual void OnDestroy();
73 |
74 | private:
75 | friend class WindowClassRegistrar;
76 |
77 | // OS callback called by message pump. Handles the WM_NCCREATE message which
78 | // is passed when the non-client area is being created and enables automatic
79 | // non-client DPI scaling so that the non-client area automatically
80 | // responds to changes in DPI. All other messages are handled by
81 | // MessageHandler.
82 | static LRESULT CALLBACK WndProc(HWND const window,
83 | UINT const message,
84 | WPARAM const wparam,
85 | LPARAM const lparam) noexcept;
86 |
87 | // Retrieves a class instance pointer for |window|
88 | static Win32Window* GetThisFromHandle(HWND const window) noexcept;
89 |
90 | // Update the window frame's theme to match the system theme.
91 | static void UpdateTheme(HWND const window);
92 |
93 | bool quit_on_close_ = false;
94 |
95 | // window handle for top level window.
96 | HWND window_handle_ = nullptr;
97 |
98 | // window handle for hosted content.
99 | HWND child_content_ = nullptr;
100 | };
101 |
102 | #endif // RUNNER_WIN32_WINDOW_H_
103 |
--------------------------------------------------------------------------------