├── .pubignore ├── lib ├── scroll_pos.dart └── src │ └── scroll_pos.dart ├── example ├── web │ ├── favicon.png │ ├── icons │ │ ├── Icon-192.png │ │ ├── Icon-512.png │ │ ├── Icon-maskable-192.png │ │ └── Icon-maskable-512.png │ ├── splash │ │ ├── img │ │ │ ├── dark-1x.png │ │ │ ├── dark-2x.png │ │ │ ├── dark-3x.png │ │ │ ├── light-1x.png │ │ │ ├── light-2x.png │ │ │ └── light-3x.png │ │ └── style.css │ ├── manifest.json │ └── index.html ├── windows │ ├── runner │ │ ├── resources │ │ │ └── app_icon.ico │ │ ├── resource.h │ │ ├── CMakeLists.txt │ │ ├── utils.h │ │ ├── runner.exe.manifest │ │ ├── flutter_window.h │ │ ├── main.cpp │ │ ├── utils.cpp │ │ ├── flutter_window.cpp │ │ ├── Runner.rc │ │ ├── win32_window.h │ │ └── win32_window.cpp │ ├── flutter │ │ ├── generated_plugin_registrant.cc │ │ ├── generated_plugin_registrant.h │ │ ├── generated_plugins.cmake │ │ └── CMakeLists.txt │ ├── .gitignore │ └── CMakeLists.txt ├── .metadata ├── pubspec.yaml ├── README.md ├── lib │ ├── main.dart │ └── listview.dart ├── .gitignore ├── analysis_options.yaml └── pubspec.lock ├── analysis_options.yaml ├── .metadata ├── pubspec.yaml ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md └── test └── scroll_pos_test.dart /.pubignore: -------------------------------------------------------------------------------- 1 | example/windows/flutter/ephemeral -------------------------------------------------------------------------------- /lib/scroll_pos.dart: -------------------------------------------------------------------------------- 1 | library scroll_pos; 2 | 3 | export 'src/scroll_pos.dart'; 4 | -------------------------------------------------------------------------------- /example/web/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WinXaito/scroll_pos/HEAD/example/web/favicon.png -------------------------------------------------------------------------------- /example/web/icons/Icon-192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WinXaito/scroll_pos/HEAD/example/web/icons/Icon-192.png -------------------------------------------------------------------------------- /example/web/icons/Icon-512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WinXaito/scroll_pos/HEAD/example/web/icons/Icon-512.png -------------------------------------------------------------------------------- /example/web/splash/img/dark-1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WinXaito/scroll_pos/HEAD/example/web/splash/img/dark-1x.png -------------------------------------------------------------------------------- /example/web/splash/img/dark-2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WinXaito/scroll_pos/HEAD/example/web/splash/img/dark-2x.png -------------------------------------------------------------------------------- /example/web/splash/img/dark-3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WinXaito/scroll_pos/HEAD/example/web/splash/img/dark-3x.png -------------------------------------------------------------------------------- /example/web/splash/img/light-1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WinXaito/scroll_pos/HEAD/example/web/splash/img/light-1x.png -------------------------------------------------------------------------------- /example/web/splash/img/light-2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WinXaito/scroll_pos/HEAD/example/web/splash/img/light-2x.png -------------------------------------------------------------------------------- /example/web/splash/img/light-3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WinXaito/scroll_pos/HEAD/example/web/splash/img/light-3x.png -------------------------------------------------------------------------------- /example/web/icons/Icon-maskable-192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WinXaito/scroll_pos/HEAD/example/web/icons/Icon-maskable-192.png -------------------------------------------------------------------------------- /example/web/icons/Icon-maskable-512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WinXaito/scroll_pos/HEAD/example/web/icons/Icon-maskable-512.png -------------------------------------------------------------------------------- /example/windows/runner/resources/app_icon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WinXaito/scroll_pos/HEAD/example/windows/runner/resources/app_icon.ico -------------------------------------------------------------------------------- /analysis_options.yaml: -------------------------------------------------------------------------------- 1 | include: package:flutter_lints/flutter.yaml 2 | 3 | # Additional information about this file can be found at 4 | # https://dart.dev/guides/language/analysis-options 5 | -------------------------------------------------------------------------------- /example/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 | -------------------------------------------------------------------------------- /.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: cf4400006550b70f28e4b4af815151d1e74846c6 8 | channel: stable 9 | 10 | project_type: package 11 | -------------------------------------------------------------------------------- /example/.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: cf4400006550b70f28e4b4af815151d1e74846c6 8 | channel: stable 9 | 10 | project_type: app 11 | -------------------------------------------------------------------------------- /example/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 | -------------------------------------------------------------------------------- /example/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 | -------------------------------------------------------------------------------- /pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: scroll_pos 2 | description: Provides some additional functions to ScrollController to define item position relative to the screen. 3 | version: 0.4.0 4 | homepage: https://github.com/WinXaito/scroll_pos 5 | 6 | environment: 7 | sdk: ">=2.15.0 <3.0.0" 8 | flutter: ">=1.17.0" 9 | 10 | dependencies: 11 | flutter: 12 | sdk: flutter 13 | 14 | dev_dependencies: 15 | flutter_test: 16 | sdk: flutter 17 | flutter_lints: ^1.0.0 18 | 19 | flutter: -------------------------------------------------------------------------------- /example/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: example 2 | description: Showcase for extended listview for Flutter 3 | publish_to: 'none' # Remove this line if you wish to publish to pub.dev 4 | version: 1.0.0+1 5 | 6 | environment: 7 | sdk: ">=2.15.0 <3.0.0" 8 | 9 | dependencies: 10 | flutter: 11 | sdk: flutter 12 | scroll_pos: 13 | path: ../ 14 | 15 | dev_dependencies: 16 | flutter_test: 17 | sdk: flutter 18 | flutter_lints: ^1.0.0 19 | 20 | flutter: 21 | uses-material-design: true 22 | -------------------------------------------------------------------------------- /example/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 | -------------------------------------------------------------------------------- /example/README.md: -------------------------------------------------------------------------------- 1 | # example 2 | 3 | Showcase for extended listview for Flutter 4 | 5 | ## Getting Started 6 | 7 | This project is a starting point for a Flutter application. 8 | 9 | A few resources to get you started if this is your first Flutter project: 10 | 11 | - [Lab: Write your first Flutter app](https://flutter.dev/docs/get-started/codelab) 12 | - [Cookbook: Useful Flutter samples](https://flutter.dev/docs/cookbook) 13 | 14 | For help getting started with Flutter, view our 15 | [online documentation](https://flutter.dev/docs), which offers tutorials, 16 | samples, guidance on mobile development, and a full API reference. 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Miscellaneous 2 | *.class 3 | *.log 4 | *.pyc 5 | *.swp 6 | .DS_Store 7 | .atom/ 8 | .buildlog/ 9 | .history 10 | .svn/ 11 | coverage 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 | # Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. 26 | /pubspec.lock 27 | **/doc/api/ 28 | .dart_tool/ 29 | .packages 30 | build/ 31 | -------------------------------------------------------------------------------- /example/windows/runner/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.14) 2 | project(runner LANGUAGES CXX) 3 | 4 | add_executable(${BINARY_NAME} WIN32 5 | "flutter_window.cpp" 6 | "main.cpp" 7 | "utils.cpp" 8 | "win32_window.cpp" 9 | "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" 10 | "Runner.rc" 11 | "runner.exe.manifest" 12 | ) 13 | apply_standard_settings(${BINARY_NAME}) 14 | target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") 15 | target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) 16 | target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") 17 | add_dependencies(${BINARY_NAME} flutter_assemble) 18 | -------------------------------------------------------------------------------- /example/web/splash/style.css: -------------------------------------------------------------------------------- 1 | body, html { 2 | margin:0; 3 | height:100%; 4 | background: #ff9800; 5 | } 6 | 7 | .center { 8 | margin: 0; 9 | position: absolute; 10 | top: 50%; 11 | left: 50%; 12 | -ms-transform: translate(-50%, -50%); 13 | transform: translate(-50%, -50%); 14 | } 15 | 16 | .contain { 17 | display:block; 18 | width:100%; height:100%; 19 | object-fit: contain; 20 | } 21 | 22 | .stretch { 23 | display:block; 24 | width:100%; height:100%; 25 | } 26 | 27 | .cover { 28 | display:block; 29 | width:100%; height:100%; 30 | object-fit: cover; 31 | } 32 | 33 | @media (prefers-color-scheme: dark) { 34 | body { 35 | margin:0; 36 | height:100%; 37 | background: #ff9800; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /example/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 | -------------------------------------------------------------------------------- /example/lib/main.dart: -------------------------------------------------------------------------------- 1 | import 'package:example/listview.dart'; 2 | import 'package:flutter/material.dart'; 3 | 4 | void main() { 5 | runApp(const MyApp()); 6 | } 7 | 8 | class MyApp extends StatelessWidget { 9 | const MyApp({Key? key}) : super(key: key); 10 | 11 | @override 12 | Widget build(BuildContext context) { 13 | return MaterialApp( 14 | title: 'ScrollPosController demo', 15 | theme: ThemeData( 16 | primarySwatch: Colors.orange, 17 | listTileTheme: ListTileThemeData( 18 | selectedTileColor: Colors.orangeAccent.withOpacity(0.3), 19 | selectedColor: Colors.black, 20 | ), 21 | ), 22 | home: Scaffold( 23 | appBar: AppBar( 24 | title: const Text('ScrollPosController Demo'), 25 | ), 26 | body: const ExampleListView(), 27 | ), 28 | ); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /example/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 | -------------------------------------------------------------------------------- /example/.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 | **/doc/api/ 25 | **/ios/Flutter/.last_build_id 26 | .dart_tool/ 27 | .flutter-plugins 28 | .flutter-plugins-dependencies 29 | .packages 30 | .pub-cache/ 31 | .pub/ 32 | /build/ 33 | 34 | # Web related 35 | lib/generated_plugin_registrant.dart 36 | 37 | # Symbolication related 38 | app.*.symbols 39 | 40 | # Obfuscation related 41 | app.*.map.json 42 | 43 | # Android Studio will place build artifacts here 44 | /android/app/debug 45 | /android/app/profile 46 | /android/app/release 47 | -------------------------------------------------------------------------------- /example/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 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## [next] 2 | 3 | ## 0.5.0 - 19/10/2023 4 | 5 | - **BREAKING CHANGE**: Fix `canBackward` and `canForward` methods. These methods had a bad behaviour. 6 | - Add `atStart` and `atEnd` attribute to indicate if the scrollbar is at the top or the bottom. 7 | - Add `forwardPage` and `backwardPage` methods to move by the inside view distance (generally, this is the comportment of the page up/down). 8 | - Give access to the method `scrollToPos`. 9 | 10 | ## 0.4.0 - 08/05/2023 11 | 12 | - Add more checks to avoid error or division by zero ([#1](https://github.com/WinXaito/scroll_pos/pull/1)) 13 | 14 | ## 0.3.0 - 24/12/2021 15 | 16 | - *Breaking*: rename methods (replace terms `Top` and `Bottom` by `Start` and `End`, because the scrollbar can be horizontal) 17 | - Fix `animate` parameter on differents methods (didn't work as expected) 18 | - Add fields (`canScroll`, `canForward`, `canBackward`) 19 | 20 | ## 0.2.0 - 24/12/2021 21 | 22 | - Add methods `forward` and `backward` 23 | 24 | ## 0.1.0 - 18/12/2021 25 | 26 | - Initial Release -------------------------------------------------------------------------------- /example/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 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 WinXaito 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /example/web/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ScrollPosController", 3 | "short_name": "scroll_pos", 4 | "start_url": ".", 5 | "display": "standalone", 6 | "background_color": "#fb8c00", 7 | "theme_color": "#ff9800", 8 | "description": "A controller that allow you to place item at specific position on the screen.", 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Scroll Position 2 | 3 | Provides some additional functions to ScrollController 4 | to define item position relative to the screen. 5 | 6 | A live version is available [here](https://flutter.winxaito.com/scroll_pos/). 7 | 8 | ![scrollpos_demo](https://user-images.githubusercontent.com/8223773/146646121-c7b702d4-e82e-4d95-b1b0-85377d7d3745.gif) 9 | 10 | > Note: this works on condition that all items have the same height ! 11 | 12 | ## Usage 13 | 14 | ```dart 15 | // Create a ScrollPosController (don't forget to set and update itemCount !) 16 | final controller = ScrollPosController(itemCount: itemCount); 17 | 18 | // Assign the controller to a scrollable item (like an ListView) 19 | ListView( 20 | controller: controller, 21 | children: [ 22 | ... 23 | ]; 24 | ); 25 | 26 | // Control the controller 27 | TextButton( 28 | child: Text('To item'), 29 | onPressed: () { 30 | setState(() { 31 | controller.scrollToItem(index); 32 | }); 33 | }, 34 | ); 35 | ``` 36 | 37 | ## Main methods 38 | 39 | - `void scrollTop({bool? animate})` : Go to the first item 40 | - `void scrollBottom({bool? animate})` : Go to the last item 41 | - `void scrollToItem(int index, {bool? animate, bool center = false})` : Makes the item visible on the screen -------------------------------------------------------------------------------- /example/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.CreateAndShow(L"example", 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 | -------------------------------------------------------------------------------- /example/web/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | ScrollPosController 17 | 18 | 19 | 20 | 21 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /example/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 17 | # https://dart-lang.github.io/linter/lints/index.html. 18 | # 19 | # Instead of disabling a lint rule for the entire project in the 20 | # section below, it can also be suppressed for a single line of code 21 | # or a specific dart file by using the `// ignore: name_of_lint` and 22 | # `// ignore_for_file: name_of_lint` syntax on the line or in the file 23 | # producing the lint. 24 | rules: 25 | # avoid_print: false # Uncomment to disable the `avoid_print` rule 26 | # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule 27 | 28 | # Additional information about this file can be found at 29 | # https://dart.dev/guides/language/analysis-options 30 | -------------------------------------------------------------------------------- /example/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 | if (target_length == 0) { 52 | return std::string(); 53 | } 54 | std::string utf8_string; 55 | utf8_string.resize(target_length); 56 | int converted_length = ::WideCharToMultiByte( 57 | CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, 58 | -1, utf8_string.data(), 59 | target_length, nullptr, nullptr); 60 | if (converted_length == 0) { 61 | return std::string(); 62 | } 63 | return utf8_string; 64 | } 65 | -------------------------------------------------------------------------------- /example/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 | return true; 30 | } 31 | 32 | void FlutterWindow::OnDestroy() { 33 | if (flutter_controller_) { 34 | flutter_controller_ = nullptr; 35 | } 36 | 37 | Win32Window::OnDestroy(); 38 | } 39 | 40 | LRESULT 41 | FlutterWindow::MessageHandler(HWND hwnd, UINT const message, 42 | WPARAM const wparam, 43 | LPARAM const lparam) noexcept { 44 | // Give Flutter, including plugins, an opportunity to handle window messages. 45 | if (flutter_controller_) { 46 | std::optional result = 47 | flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, 48 | lparam); 49 | if (result) { 50 | return *result; 51 | } 52 | } 53 | 54 | switch (message) { 55 | case WM_FONTCHANGE: 56 | flutter_controller_->engine()->ReloadSystemFonts(); 57 | break; 58 | } 59 | 60 | return Win32Window::MessageHandler(hwnd, message, wparam, lparam); 61 | } 62 | -------------------------------------------------------------------------------- /example/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.winxaito" "\0" 93 | VALUE "FileDescription", "Showcase for extended listview for Flutter" "\0" 94 | VALUE "FileVersion", VERSION_AS_STRING "\0" 95 | VALUE "InternalName", "example" "\0" 96 | VALUE "LegalCopyright", "Copyright (C) 2021 com.winxaito. All rights reserved." "\0" 97 | VALUE "OriginalFilename", "example.exe" "\0" 98 | VALUE "ProductName", "example" "\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 | -------------------------------------------------------------------------------- /example/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 and shows a win32 window with |title| and position and size 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 to will treat the width height passed in to this function 35 | // as logical pixels and scale to appropriate for the default monitor. Returns 36 | // true if the window was created successfully. 37 | bool CreateAndShow(const std::wstring& title, 38 | const Point& origin, 39 | const Size& size); 40 | 41 | // Release OS resources associated with window. 42 | void Destroy(); 43 | 44 | // Inserts |content| into the window tree. 45 | void SetChildContent(HWND content); 46 | 47 | // Returns the backing Window handle to enable clients to set icon and other 48 | // window properties. Returns nullptr if the window has been destroyed. 49 | HWND GetHandle(); 50 | 51 | // If true, closing this window will quit the application. 52 | void SetQuitOnClose(bool quit_on_close); 53 | 54 | // Return a RECT representing the bounds of the current client area. 55 | RECT GetClientArea(); 56 | 57 | protected: 58 | // Processes and route salient window messages for mouse handling, 59 | // size change and DPI. Delegates handling of these to member overloads that 60 | // inheriting classes can handle. 61 | virtual LRESULT MessageHandler(HWND window, 62 | UINT const message, 63 | WPARAM const wparam, 64 | LPARAM const lparam) noexcept; 65 | 66 | // Called when CreateAndShow is called, allowing subclass window-related 67 | // setup. Subclasses should return false if setup fails. 68 | virtual bool OnCreate(); 69 | 70 | // Called when Destroy is called. 71 | virtual void OnDestroy(); 72 | 73 | private: 74 | friend class WindowClassRegistrar; 75 | 76 | // OS callback called by message pump. Handles the WM_NCCREATE message which 77 | // is passed when the non-client area is being created and enables automatic 78 | // non-client DPI scaling so that the non-client area automatically 79 | // responsponds to changes in DPI. All other messages are handled by 80 | // MessageHandler. 81 | static LRESULT CALLBACK WndProc(HWND const window, 82 | UINT const message, 83 | WPARAM const wparam, 84 | LPARAM const lparam) noexcept; 85 | 86 | // Retrieves a class instance pointer for |window| 87 | static Win32Window* GetThisFromHandle(HWND const window) noexcept; 88 | 89 | bool quit_on_close_ = false; 90 | 91 | // window handle for top level window. 92 | HWND window_handle_ = nullptr; 93 | 94 | // window handle for hosted content. 95 | HWND child_content_ = nullptr; 96 | }; 97 | 98 | #endif // RUNNER_WIN32_WINDOW_H_ 99 | -------------------------------------------------------------------------------- /example/windows/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.14) 2 | project(example LANGUAGES CXX) 3 | 4 | set(BINARY_NAME "example") 5 | 6 | cmake_policy(SET CMP0063 NEW) 7 | 8 | set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") 9 | 10 | # Configure build options. 11 | get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) 12 | if(IS_MULTICONFIG) 13 | set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" 14 | CACHE STRING "" FORCE) 15 | else() 16 | if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) 17 | set(CMAKE_BUILD_TYPE "Debug" CACHE 18 | STRING "Flutter build mode" FORCE) 19 | set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS 20 | "Debug" "Profile" "Release") 21 | endif() 22 | endif() 23 | 24 | set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") 25 | set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") 26 | set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") 27 | set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") 28 | 29 | # Use Unicode for all projects. 30 | add_definitions(-DUNICODE -D_UNICODE) 31 | 32 | # Compilation settings that should be applied to most targets. 33 | function(APPLY_STANDARD_SETTINGS TARGET) 34 | target_compile_features(${TARGET} PUBLIC cxx_std_17) 35 | target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") 36 | target_compile_options(${TARGET} PRIVATE /EHsc) 37 | target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") 38 | target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") 39 | endfunction() 40 | 41 | set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") 42 | 43 | # Flutter library and tool build rules. 44 | add_subdirectory(${FLUTTER_MANAGED_DIR}) 45 | 46 | # Application build 47 | add_subdirectory("runner") 48 | 49 | # Generated plugin build rules, which manage building the plugins and adding 50 | # them to the application. 51 | include(flutter/generated_plugins.cmake) 52 | 53 | 54 | # === Installation === 55 | # Support files are copied into place next to the executable, so that it can 56 | # run in place. This is done instead of making a separate bundle (as on Linux) 57 | # so that building and running from within Visual Studio will work. 58 | set(BUILD_BUNDLE_DIR "$") 59 | # Make the "install" step default, as it's required to run. 60 | set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) 61 | if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) 62 | set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) 63 | endif() 64 | 65 | set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") 66 | set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") 67 | 68 | install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" 69 | COMPONENT Runtime) 70 | 71 | install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" 72 | COMPONENT Runtime) 73 | 74 | install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 75 | COMPONENT Runtime) 76 | 77 | if(PLUGIN_BUNDLED_LIBRARIES) 78 | install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" 79 | DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 80 | COMPONENT Runtime) 81 | endif() 82 | 83 | # Fully re-copy the assets directory on each build to avoid having stale files 84 | # from a previous install. 85 | set(FLUTTER_ASSET_DIR_NAME "flutter_assets") 86 | install(CODE " 87 | file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") 88 | " COMPONENT Runtime) 89 | install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" 90 | DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) 91 | 92 | # Install the AOT library on non-Debug builds only. 93 | install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" 94 | CONFIGURATIONS Profile;Release 95 | COMPONENT Runtime) 96 | -------------------------------------------------------------------------------- /example/windows/flutter/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.14) 2 | 3 | set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") 4 | 5 | # Configuration provided via flutter tool. 6 | include(${EPHEMERAL_DIR}/generated_config.cmake) 7 | 8 | # TODO: Move the rest of this into files in ephemeral. See 9 | # https://github.com/flutter/flutter/issues/57146. 10 | set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") 11 | 12 | # === Flutter Library === 13 | set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") 14 | 15 | # Published to parent scope for install step. 16 | set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) 17 | set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) 18 | set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) 19 | set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) 20 | 21 | list(APPEND FLUTTER_LIBRARY_HEADERS 22 | "flutter_export.h" 23 | "flutter_windows.h" 24 | "flutter_messenger.h" 25 | "flutter_plugin_registrar.h" 26 | "flutter_texture_registrar.h" 27 | ) 28 | list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") 29 | add_library(flutter INTERFACE) 30 | target_include_directories(flutter INTERFACE 31 | "${EPHEMERAL_DIR}" 32 | ) 33 | target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") 34 | add_dependencies(flutter flutter_assemble) 35 | 36 | # === Wrapper === 37 | list(APPEND CPP_WRAPPER_SOURCES_CORE 38 | "core_implementations.cc" 39 | "standard_codec.cc" 40 | ) 41 | list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") 42 | list(APPEND CPP_WRAPPER_SOURCES_PLUGIN 43 | "plugin_registrar.cc" 44 | ) 45 | list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") 46 | list(APPEND CPP_WRAPPER_SOURCES_APP 47 | "flutter_engine.cc" 48 | "flutter_view_controller.cc" 49 | ) 50 | list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") 51 | 52 | # Wrapper sources needed for a plugin. 53 | add_library(flutter_wrapper_plugin STATIC 54 | ${CPP_WRAPPER_SOURCES_CORE} 55 | ${CPP_WRAPPER_SOURCES_PLUGIN} 56 | ) 57 | apply_standard_settings(flutter_wrapper_plugin) 58 | set_target_properties(flutter_wrapper_plugin PROPERTIES 59 | POSITION_INDEPENDENT_CODE ON) 60 | set_target_properties(flutter_wrapper_plugin PROPERTIES 61 | CXX_VISIBILITY_PRESET hidden) 62 | target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) 63 | target_include_directories(flutter_wrapper_plugin PUBLIC 64 | "${WRAPPER_ROOT}/include" 65 | ) 66 | add_dependencies(flutter_wrapper_plugin flutter_assemble) 67 | 68 | # Wrapper sources needed for the runner. 69 | add_library(flutter_wrapper_app STATIC 70 | ${CPP_WRAPPER_SOURCES_CORE} 71 | ${CPP_WRAPPER_SOURCES_APP} 72 | ) 73 | apply_standard_settings(flutter_wrapper_app) 74 | target_link_libraries(flutter_wrapper_app PUBLIC flutter) 75 | target_include_directories(flutter_wrapper_app PUBLIC 76 | "${WRAPPER_ROOT}/include" 77 | ) 78 | add_dependencies(flutter_wrapper_app flutter_assemble) 79 | 80 | # === Flutter tool backend === 81 | # _phony_ is a non-existent file to force this command to run every time, 82 | # since currently there's no way to get a full input/output list from the 83 | # flutter tool. 84 | set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") 85 | set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) 86 | add_custom_command( 87 | OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} 88 | ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} 89 | ${CPP_WRAPPER_SOURCES_APP} 90 | ${PHONY_OUTPUT} 91 | COMMAND ${CMAKE_COMMAND} -E env 92 | ${FLUTTER_TOOL_ENVIRONMENT} 93 | "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" 94 | windows-x64 $ 95 | VERBATIM 96 | ) 97 | add_custom_target(flutter_assemble DEPENDS 98 | "${FLUTTER_LIBRARY}" 99 | ${FLUTTER_LIBRARY_HEADERS} 100 | ${CPP_WRAPPER_SOURCES_CORE} 101 | ${CPP_WRAPPER_SOURCES_PLUGIN} 102 | ${CPP_WRAPPER_SOURCES_APP} 103 | ) 104 | -------------------------------------------------------------------------------- /example/lib/listview.dart: -------------------------------------------------------------------------------- 1 | import 'package:scroll_pos/scroll_pos.dart'; 2 | import 'package:flutter/material.dart'; 3 | 4 | class ExampleListView extends StatefulWidget { 5 | const ExampleListView({Key? key}) : super(key: key); 6 | 7 | @override 8 | State createState() => _ExampleListViewState(); 9 | } 10 | 11 | class _ExampleListViewState extends State { 12 | static const itemCount = 50; 13 | final controller = ScrollPosController(itemCount: itemCount); 14 | int selected = 0; 15 | bool center = false; 16 | 17 | void rebuild() => setState((){}); 18 | 19 | @override 20 | void initState() { 21 | controller.addListener(rebuild); 22 | super.initState(); 23 | } 24 | 25 | @override 26 | void dispose() { 27 | controller.removeListener(rebuild); 28 | controller.dispose(); 29 | super.dispose(); 30 | } 31 | 32 | @override 33 | Widget build(BuildContext context) { 34 | return Column( 35 | children: [ 36 | _controls(context), 37 | Expanded( 38 | child: ListView.builder( 39 | controller: controller, 40 | itemCount: itemCount, 41 | itemBuilder: (context, index) { 42 | return ListTile( 43 | selected: selected == index, 44 | leading: Text('$index'), 45 | title: const Text('Tile'), 46 | ); 47 | }, 48 | ), 49 | ), 50 | ], 51 | ); 52 | } 53 | 54 | Widget _controls(BuildContext context) { 55 | Widget child; 56 | final items = _controlItems(context); 57 | if (MediaQuery.of(context).size.width > 700) { 58 | child = Row( 59 | mainAxisAlignment: MainAxisAlignment.spaceAround, 60 | children: items, 61 | ); 62 | } else { 63 | child = Column( 64 | children: [ 65 | Row( 66 | mainAxisAlignment: MainAxisAlignment.spaceAround, 67 | children: items.getRange(0, 4).toList(), 68 | ), 69 | Row( 70 | mainAxisAlignment: MainAxisAlignment.spaceAround, 71 | children: items.getRange(4, items.length).toList(), 72 | ), 73 | ], 74 | ); 75 | } 76 | 77 | return Container( 78 | color: Theme.of(context).scaffoldBackgroundColor, 79 | child: Padding( 80 | padding: const EdgeInsets.all(10), 81 | child: child, 82 | ), 83 | ); 84 | } 85 | 86 | List _controlItems(BuildContext context) { 87 | return [ 88 | _bt('Top', () { 89 | selected = 0; 90 | controller.scrollToStart(); 91 | }), 92 | _bt('Bottom', () { 93 | selected = itemCount - 1; 94 | controller.scrollToEnd(); 95 | }), 96 | _bt('Previous', () { 97 | if (selected > 0) { 98 | selected--; 99 | } 100 | controller.scrollToItem(selected, center: center); 101 | }), 102 | _bt('Next', () { 103 | if (selected < itemCount - 1) { 104 | selected++; 105 | } 106 | controller.scrollToItem(selected, center: center); 107 | }), 108 | _bt('Backward', () { 109 | controller.backward(); 110 | }, enabled: controller.canBackward), 111 | _bt('Forward', () { 112 | controller.forward(); 113 | }, enabled: controller.canForward), 114 | _bt('Page backward', () { 115 | controller.backwardPage(); 116 | selected -= controller.visibleItems.floor(); 117 | if(selected < 0){ 118 | selected = 0; 119 | } 120 | }, enabled: controller.canBackward || selected != 0), 121 | _bt('Page forward', () { 122 | controller.forwardPage(); 123 | selected += controller.visibleItems.floor(); 124 | if(selected >= itemCount){ 125 | selected = itemCount - 1; 126 | } 127 | }, enabled: controller.canForward || selected != itemCount - 1), 128 | Row( 129 | children: [ 130 | const Text('Animation:'), 131 | Switch( 132 | value: controller.animate, 133 | onChanged: (v) { 134 | setState(() { 135 | controller.animate = v; 136 | }); 137 | }, 138 | ), 139 | ], 140 | ), 141 | Row( 142 | children: [ 143 | const Text('Center:'), 144 | Switch( 145 | value: center, 146 | onChanged: (v) { 147 | setState(() { 148 | center = v; 149 | }); 150 | }, 151 | ), 152 | ], 153 | ), 154 | ]; 155 | } 156 | 157 | Widget _bt(String text, VoidCallback onPressed, {bool enabled = true}) { 158 | return TextButton( 159 | child: Text(text), 160 | onPressed: enabled ? () { 161 | setState(() { 162 | onPressed(); 163 | }); 164 | } : null, 165 | ); 166 | } 167 | } 168 | -------------------------------------------------------------------------------- /example/pubspec.lock: -------------------------------------------------------------------------------- 1 | # Generated by pub 2 | # See https://dart.dev/tools/pub/glossary#lockfile 3 | packages: 4 | async: 5 | dependency: transitive 6 | description: 7 | name: async 8 | sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" 9 | url: "https://pub.dev" 10 | source: hosted 11 | version: "2.11.0" 12 | boolean_selector: 13 | dependency: transitive 14 | description: 15 | name: boolean_selector 16 | sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66" 17 | url: "https://pub.dev" 18 | source: hosted 19 | version: "2.1.1" 20 | characters: 21 | dependency: transitive 22 | description: 23 | name: characters 24 | sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605" 25 | url: "https://pub.dev" 26 | source: hosted 27 | version: "1.3.0" 28 | clock: 29 | dependency: transitive 30 | description: 31 | name: clock 32 | sha256: cb6d7f03e1de671e34607e909a7213e31d7752be4fb66a86d29fe1eb14bfb5cf 33 | url: "https://pub.dev" 34 | source: hosted 35 | version: "1.1.1" 36 | collection: 37 | dependency: transitive 38 | description: 39 | name: collection 40 | sha256: "4a07be6cb69c84d677a6c3096fcf960cc3285a8330b4603e0d463d15d9bd934c" 41 | url: "https://pub.dev" 42 | source: hosted 43 | version: "1.17.1" 44 | fake_async: 45 | dependency: transitive 46 | description: 47 | name: fake_async 48 | sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78" 49 | url: "https://pub.dev" 50 | source: hosted 51 | version: "1.3.1" 52 | flutter: 53 | dependency: "direct main" 54 | description: flutter 55 | source: sdk 56 | version: "0.0.0" 57 | flutter_lints: 58 | dependency: "direct dev" 59 | description: 60 | name: flutter_lints 61 | sha256: b543301ad291598523947dc534aaddc5aaad597b709d2426d3a0e0d44c5cb493 62 | url: "https://pub.dev" 63 | source: hosted 64 | version: "1.0.4" 65 | flutter_test: 66 | dependency: "direct dev" 67 | description: flutter 68 | source: sdk 69 | version: "0.0.0" 70 | js: 71 | dependency: transitive 72 | description: 73 | name: js 74 | sha256: f2c445dce49627136094980615a031419f7f3eb393237e4ecd97ac15dea343f3 75 | url: "https://pub.dev" 76 | source: hosted 77 | version: "0.6.7" 78 | lints: 79 | dependency: transitive 80 | description: 81 | name: lints 82 | sha256: a2c3d198cb5ea2e179926622d433331d8b58374ab8f29cdda6e863bd62fd369c 83 | url: "https://pub.dev" 84 | source: hosted 85 | version: "1.0.1" 86 | matcher: 87 | dependency: transitive 88 | description: 89 | name: matcher 90 | sha256: "6501fbd55da300384b768785b83e5ce66991266cec21af89ab9ae7f5ce1c4cbb" 91 | url: "https://pub.dev" 92 | source: hosted 93 | version: "0.12.15" 94 | material_color_utilities: 95 | dependency: transitive 96 | description: 97 | name: material_color_utilities 98 | sha256: d92141dc6fe1dad30722f9aa826c7fbc896d021d792f80678280601aff8cf724 99 | url: "https://pub.dev" 100 | source: hosted 101 | version: "0.2.0" 102 | meta: 103 | dependency: transitive 104 | description: 105 | name: meta 106 | sha256: "3c74dbf8763d36539f114c799d8a2d87343b5067e9d796ca22b5eb8437090ee3" 107 | url: "https://pub.dev" 108 | source: hosted 109 | version: "1.9.1" 110 | path: 111 | dependency: transitive 112 | description: 113 | name: path 114 | sha256: "8829d8a55c13fc0e37127c29fedf290c102f4e40ae94ada574091fe0ff96c917" 115 | url: "https://pub.dev" 116 | source: hosted 117 | version: "1.8.3" 118 | scroll_pos: 119 | dependency: "direct main" 120 | description: 121 | path: ".." 122 | relative: true 123 | source: path 124 | version: "0.4.0" 125 | sky_engine: 126 | dependency: transitive 127 | description: flutter 128 | source: sdk 129 | version: "0.0.99" 130 | source_span: 131 | dependency: transitive 132 | description: 133 | name: source_span 134 | sha256: dd904f795d4b4f3b870833847c461801f6750a9fa8e61ea5ac53f9422b31f250 135 | url: "https://pub.dev" 136 | source: hosted 137 | version: "1.9.1" 138 | stack_trace: 139 | dependency: transitive 140 | description: 141 | name: stack_trace 142 | sha256: c3c7d8edb15bee7f0f74debd4b9c5f3c2ea86766fe4178eb2a18eb30a0bdaed5 143 | url: "https://pub.dev" 144 | source: hosted 145 | version: "1.11.0" 146 | stream_channel: 147 | dependency: transitive 148 | description: 149 | name: stream_channel 150 | sha256: "83615bee9045c1d322bbbd1ba209b7a749c2cbcdcb3fdd1df8eb488b3279c1c8" 151 | url: "https://pub.dev" 152 | source: hosted 153 | version: "2.1.1" 154 | string_scanner: 155 | dependency: transitive 156 | description: 157 | name: string_scanner 158 | sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde" 159 | url: "https://pub.dev" 160 | source: hosted 161 | version: "1.2.0" 162 | term_glyph: 163 | dependency: transitive 164 | description: 165 | name: term_glyph 166 | sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84 167 | url: "https://pub.dev" 168 | source: hosted 169 | version: "1.2.1" 170 | test_api: 171 | dependency: transitive 172 | description: 173 | name: test_api 174 | sha256: eb6ac1540b26de412b3403a163d919ba86f6a973fe6cc50ae3541b80092fdcfb 175 | url: "https://pub.dev" 176 | source: hosted 177 | version: "0.5.1" 178 | vector_math: 179 | dependency: transitive 180 | description: 181 | name: vector_math 182 | sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" 183 | url: "https://pub.dev" 184 | source: hosted 185 | version: "2.1.4" 186 | sdks: 187 | dart: ">=3.0.0-0 <4.0.0" 188 | flutter: ">=1.17.0" 189 | -------------------------------------------------------------------------------- /lib/src/scroll_pos.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/widgets.dart'; 2 | 3 | const _kDefaultAnimationDuration = Duration(milliseconds: 300); 4 | const _kDefaultAnimationCurve = Curves.ease; 5 | 6 | /// Controls a scrollable widget. 7 | /// 8 | /// This class extends [ScrollController] and adds functionality to it. 9 | /// A ScrollPosController allow you to place an item on a specific area 10 | /// of the screen. 11 | class ScrollPosController extends ScrollController { 12 | int itemCount; 13 | bool animate; 14 | Duration animationDuration; 15 | Curve animationCurve; 16 | 17 | ScrollPosController({ 18 | this.itemCount = 0, 19 | this.animate = true, 20 | this.animationDuration = _kDefaultAnimationDuration, 21 | this.animationCurve = _kDefaultAnimationCurve, 22 | double initialScrollOffset = 0.0, 23 | bool keepScrollOffset = true, 24 | String? debugLabel, 25 | }) : super( 26 | initialScrollOffset: initialScrollOffset, 27 | keepScrollOffset: keepScrollOffset, 28 | debugLabel: debugLabel, 29 | ); 30 | 31 | @visibleForTesting 32 | double get inside => positions.isNotEmpty && position.hasContentDimensions 33 | ? position.extentInside 34 | : 0; 35 | 36 | @visibleForTesting 37 | double get max => positions.isNotEmpty && position.hasContentDimensions 38 | ? position.maxScrollExtent 39 | : 0; 40 | 41 | /// total returns the total of the inside part and the scrollable part. 42 | double get total => inside + max; 43 | 44 | @override 45 | double get offset => 46 | positions.isNotEmpty && position.hasPixels ? super.offset : 0; 47 | 48 | /// scrollPerItem returns the quantity of scroll needed for travel 49 | /// the height of one item. 50 | double get scrollPerItem => itemCount > 0 ? total / itemCount : 0; 51 | 52 | /// visibleItems returns the quantity of items visible in the screen. 53 | double get visibleItems => scrollPerItem > 0 ? inside / scrollPerItem : 0; 54 | 55 | /// canScroll indicate if this widget has scrollable content 56 | bool get canScroll => max > 0; 57 | 58 | /// atStart indicate if the scroll is at the start position (offset 0) 59 | bool get atStart => offset == 0.0; 60 | 61 | /// atEnd indicate if the scroll is at the end position (offset max) 62 | bool get atEnd => offset == max; 63 | 64 | /// canForward indicate if the scrollbar can go to a next element (!atEnd). 65 | bool get canForward => !atEnd; 66 | 67 | /// canBackward indicate if the scrollbar can go to a previous element (!atStart). 68 | bool get canBackward => !atStart; 69 | 70 | /// scrollTop will move the scrollbar to the top (first item). 71 | void scrollToStart({bool? animate}) { 72 | scrollToPos(0, animate: animate); 73 | } 74 | 75 | /// scrollBottom will move the scrollbar to the bottom (last item). 76 | void scrollToEnd({bool? animate}) { 77 | scrollToPos(max, animate: animate); 78 | } 79 | 80 | /// scrollToItem will move the scrollbar to make the item 81 | /// (defined by its index) visible on the screen. 82 | /// If the item is already fully visible in the screen, the scrollbar 83 | /// is not moved. 84 | void scrollToItem(int index, {bool? animate, bool center = false}) { 85 | _scrollOffItem(index, animate: animate, center: center); 86 | } 87 | 88 | /// backward will move the scrollbar with a distance of one item in 89 | /// the bottom direction. 90 | /// If value of align is `true`, the last visible item will be aligned. 91 | void forward({bool align = true, bool? animate}) { 92 | if (align) { 93 | final lastIdx = ((offset + inside) / scrollPerItem - 1).floor() + 1; 94 | if (lastIdx >= itemCount) { 95 | return; 96 | } 97 | scrollToItem(lastIdx, animate: animate); 98 | } else { 99 | scrollToPos(offset + scrollPerItem, animate: animate); 100 | } 101 | } 102 | 103 | /// backward will move the scrollbar with a distance of one item in 104 | /// the top direction. 105 | /// If value of align is `true`, the first visible item will be aligned. 106 | void backward({bool align = true, bool? animate}) { 107 | if (align) { 108 | final firstIdx = (offset / scrollPerItem - 1).ceil(); 109 | if (firstIdx < 0) { 110 | return; 111 | } 112 | scrollToItem(firstIdx, animate: animate); 113 | } else { 114 | scrollToPos(offset - scrollPerItem, animate: animate); 115 | } 116 | } 117 | 118 | /// forwardPage will move the scrollbar with a distance of the inside view 119 | /// in the bottom direction. 120 | void forwardPage({bool align = true, bool? animate}) { 121 | final o = align ? offset + (visibleItems.floor() * scrollPerItem) : offset + inside; 122 | scrollToPos(o, animate: animate); 123 | } 124 | 125 | /// backwardPage will move the scrollbar with a distance of the inside view 126 | /// in the top direction. 127 | void backwardPage({bool align = true, bool? animate}){ 128 | final o = align ? offset - (visibleItems.floor() * scrollPerItem) : offset - inside; 129 | scrollToPos(o, animate: animate); 130 | } 131 | 132 | /// scrollOffItemCenter return the offset when the item is placed at 133 | /// the center of the screen. 134 | double scrollOffItemCenter(int index) { 135 | return (index + 1) * scrollPerItem - inside / 2; 136 | } 137 | 138 | /// scrollOfItemBottom return the offset when the item is placed at 139 | /// the bottom of the screen. 140 | double scrollOffItemEnd(int index) { 141 | return (index + 1) * scrollPerItem - inside; 142 | } 143 | 144 | /// scrollOffItemTop return the offset when the item is placed at 145 | /// the top of the screen. 146 | double scrollOffItemStart(int index) { 147 | return index * scrollPerItem; 148 | } 149 | 150 | void scrollToPos(double offset, {bool? animate}) { 151 | if (((animate != null && animate) || (animate == null && this.animate)) && 152 | animationDuration != Duration.zero) { 153 | animateTo( 154 | offset.clamp(0, max), 155 | duration: animationDuration, 156 | curve: animationCurve, 157 | ); 158 | } else { 159 | jumpTo(offset.clamp(0, max)); 160 | } 161 | } 162 | 163 | void _scrollOffItem(int index, {bool? animate, bool center = false}) { 164 | final centerVal = scrollOffItemCenter(index); 165 | final endVal = scrollOffItemEnd(index); 166 | final startVal = scrollOffItemStart(index); 167 | 168 | if (center) { 169 | scrollToPos(centerVal, animate: animate); 170 | } else if (offset < endVal) { 171 | scrollToPos(endVal, animate: animate); 172 | } else if (offset > startVal) { 173 | scrollToPos(startVal, animate: animate); 174 | } 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /test/scroll_pos_test.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | import 'package:flutter_test/flutter_test.dart'; 3 | import 'package:scroll_pos/scroll_pos.dart'; 4 | 5 | class FakeScrollPosController extends ScrollPosController { 6 | double _offset = 0; 7 | final double _max; 8 | final double _inside; 9 | 10 | @override 11 | double get offset => _offset; 12 | 13 | @override 14 | double get inside => _inside; 15 | 16 | @override 17 | double get max => _max; 18 | 19 | FakeScrollPosController( 20 | this._max, 21 | this._inside, 22 | int itemCount, 23 | ) : super(itemCount: itemCount); 24 | 25 | @override 26 | void jumpTo(double offset) { 27 | _offset = offset; 28 | } 29 | 30 | @override 31 | Future animateTo( 32 | double offset, { 33 | required Duration duration, 34 | required Curve curve, 35 | }) async { 36 | _offset = offset; 37 | } 38 | } 39 | 40 | void main() { 41 | const max = 200.0; 42 | const inside = 100.0; 43 | const itemCount = 15; 44 | 45 | final controller = FakeScrollPosController(max, inside, itemCount); 46 | final emptyController = FakeScrollPosController(0, 0, 0); 47 | 48 | test('Default values', () { 49 | expect(controller.animate, true); 50 | expect(controller.itemCount, itemCount); 51 | }); 52 | 53 | test('Empty list', () { 54 | expect(emptyController.animate, true); 55 | expect(emptyController.itemCount, 0); 56 | expect(emptyController.scrollPerItem, 0); 57 | expect(emptyController.max, 0); 58 | expect(emptyController.offset, 0); 59 | emptyController.scrollToEnd(); 60 | expect(emptyController.offset, 0); 61 | }); 62 | 63 | test('Scroll per item', () { 64 | expect(controller.scrollPerItem, (max + inside) / itemCount); 65 | }); 66 | 67 | test('Visible items', () { 68 | expect(controller.visibleItems, inside / controller.scrollPerItem); 69 | }); 70 | 71 | test('ScrollBottom', () { 72 | controller.scrollToEnd(); 73 | expect(controller.max != 0, true); 74 | expect(controller.offset, controller.max); 75 | }); 76 | 77 | test('ScrollTop', () { 78 | controller.scrollToStart(); 79 | expect(controller.offset, 0); 80 | }); 81 | 82 | test('ScrollToItem-FromBottom-top', () { 83 | controller.scrollToEnd(); 84 | controller.scrollToItem(0); 85 | expect(controller.offset, 0); 86 | }); 87 | 88 | test('ScrollToItem-FromTop-bottom', () { 89 | controller.scrollToStart(); 90 | controller.scrollToItem(itemCount - 1); 91 | expect(controller.offset, max); 92 | }); 93 | 94 | test('ScrollToItem-FromTop-middle', () { 95 | controller.scrollToStart(); 96 | controller.scrollToItem(itemCount - 2); 97 | expect(controller.offset, max - controller.scrollPerItem); 98 | }); 99 | 100 | test('ScrollToItem-FromBottom-middle', () { 101 | controller.scrollToEnd(); 102 | controller.scrollToItem(1); 103 | expect(controller.offset, controller.scrollPerItem); 104 | }); 105 | 106 | test('ScrollToItem-top', () { 107 | controller.scrollToStart(); 108 | controller.scrollToItem(0, center: true); 109 | expect(controller.offset, 0); 110 | }); 111 | 112 | test('ScrollToItem-bottom', () { 113 | controller.scrollToStart(); 114 | controller.scrollToItem(itemCount - 1, center: true); 115 | expect(controller.offset, max); 116 | }); 117 | 118 | test('ScrollToItem-center', () { 119 | controller.scrollToStart(); 120 | final idx = (itemCount / 2).floor(); 121 | controller.scrollToItem(idx, center: true); 122 | expect( 123 | controller.offset, (idx + 1) * controller.scrollPerItem - inside / 2); 124 | }); 125 | 126 | test('ScrollForward', () { 127 | controller.scrollToStart(); 128 | controller.forward(); 129 | final expected = controller.scrollPerItem; 130 | expect(controller.offset, expected); 131 | }); 132 | 133 | test('ScrollBackward', () { 134 | controller.scrollToEnd(); 135 | controller.scrollToItem(1); 136 | controller.backward(); 137 | expect(controller.offset, 0); 138 | }); 139 | 140 | test('Is At Start', (){ 141 | controller.scrollToStart(); 142 | expect(controller.atStart, true); 143 | controller.scrollToEnd(); 144 | expect(controller.atStart, false); 145 | }); 146 | 147 | test('Is At End', (){ 148 | controller.scrollToStart(); 149 | expect(controller.atEnd, false); 150 | controller.scrollToEnd(); 151 | expect(controller.atEnd, true); 152 | }); 153 | 154 | test('Can Forward', () { 155 | controller.scrollToStart(); 156 | expect(controller.canForward, true); 157 | controller.scrollToEnd(); 158 | expect(controller.canForward, false); 159 | controller.backward(); 160 | expect(controller.canForward, true); 161 | }); 162 | 163 | test('Can Backward', () { 164 | controller.scrollToStart(); 165 | expect(controller.canBackward, false); 166 | controller.scrollToEnd(); 167 | expect(controller.canBackward, true); 168 | controller.scrollToStart(); 169 | expect(controller.canBackward, false); 170 | controller.forward(); 171 | expect(controller.canBackward, true); 172 | }); 173 | 174 | test('Page forward aligned', () { 175 | controller.scrollToStart(); 176 | expect(controller.offset, 0); 177 | controller.forwardPage(); 178 | expect(controller.offset, controller.visibleItems.floor() * controller.scrollPerItem); 179 | }); 180 | 181 | test('Page backward aligned', () { 182 | controller.scrollToEnd(); 183 | expect(controller.offset, max); 184 | controller.backwardPage(); 185 | expect(controller.offset, max - controller.visibleItems.floor() * controller.scrollPerItem); 186 | }); 187 | 188 | test('Page forward not aligned', () { 189 | controller.scrollToStart(); 190 | expect(controller.offset, 0); 191 | controller.forwardPage(align: false); 192 | controller.forwardPage(align: false); 193 | expect(controller.offset, controller.inside * 2); 194 | }); 195 | 196 | test('Page backward not aligned', () { 197 | controller.scrollToEnd(); 198 | expect(controller.offset, max); 199 | controller.backwardPage(align: false); 200 | controller.backwardPage(align: false); 201 | expect(controller.offset, max - controller.inside * 2); 202 | }); 203 | 204 | test('Page forward/backward start', () { 205 | controller.scrollToStart(); 206 | expect(controller.offset, 0); 207 | controller.forwardPage(); 208 | controller.backwardPage(); 209 | expect(controller.offset, 0); 210 | }); 211 | 212 | test('page forward/backward start', () { 213 | controller.scrollToEnd(); 214 | expect(controller.offset, max); 215 | controller.backwardPage(); 216 | controller.forwardPage(); 217 | expect(controller.offset, max); 218 | }); 219 | } 220 | -------------------------------------------------------------------------------- /example/windows/runner/win32_window.cpp: -------------------------------------------------------------------------------- 1 | #include "win32_window.h" 2 | 3 | #include 4 | 5 | #include "resource.h" 6 | 7 | namespace { 8 | 9 | constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; 10 | 11 | // The number of Win32Window objects that currently exist. 12 | static int g_active_window_count = 0; 13 | 14 | using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); 15 | 16 | // Scale helper to convert logical scaler values to physical using passed in 17 | // scale factor 18 | int Scale(int source, double scale_factor) { 19 | return static_cast(source * scale_factor); 20 | } 21 | 22 | // Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. 23 | // This API is only needed for PerMonitor V1 awareness mode. 24 | void EnableFullDpiSupportIfAvailable(HWND hwnd) { 25 | HMODULE user32_module = LoadLibraryA("User32.dll"); 26 | if (!user32_module) { 27 | return; 28 | } 29 | auto enable_non_client_dpi_scaling = 30 | reinterpret_cast( 31 | GetProcAddress(user32_module, "EnableNonClientDpiScaling")); 32 | if (enable_non_client_dpi_scaling != nullptr) { 33 | enable_non_client_dpi_scaling(hwnd); 34 | FreeLibrary(user32_module); 35 | } 36 | } 37 | 38 | } // namespace 39 | 40 | // Manages the Win32Window's window class registration. 41 | class WindowClassRegistrar { 42 | public: 43 | ~WindowClassRegistrar() = default; 44 | 45 | // Returns the singleton registar instance. 46 | static WindowClassRegistrar* GetInstance() { 47 | if (!instance_) { 48 | instance_ = new WindowClassRegistrar(); 49 | } 50 | return instance_; 51 | } 52 | 53 | // Returns the name of the window class, registering the class if it hasn't 54 | // previously been registered. 55 | const wchar_t* GetWindowClass(); 56 | 57 | // Unregisters the window class. Should only be called if there are no 58 | // instances of the window. 59 | void UnregisterWindowClass(); 60 | 61 | private: 62 | WindowClassRegistrar() = default; 63 | 64 | static WindowClassRegistrar* instance_; 65 | 66 | bool class_registered_ = false; 67 | }; 68 | 69 | WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; 70 | 71 | const wchar_t* WindowClassRegistrar::GetWindowClass() { 72 | if (!class_registered_) { 73 | WNDCLASS window_class{}; 74 | window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); 75 | window_class.lpszClassName = kWindowClassName; 76 | window_class.style = CS_HREDRAW | CS_VREDRAW; 77 | window_class.cbClsExtra = 0; 78 | window_class.cbWndExtra = 0; 79 | window_class.hInstance = GetModuleHandle(nullptr); 80 | window_class.hIcon = 81 | LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); 82 | window_class.hbrBackground = 0; 83 | window_class.lpszMenuName = nullptr; 84 | window_class.lpfnWndProc = Win32Window::WndProc; 85 | RegisterClass(&window_class); 86 | class_registered_ = true; 87 | } 88 | return kWindowClassName; 89 | } 90 | 91 | void WindowClassRegistrar::UnregisterWindowClass() { 92 | UnregisterClass(kWindowClassName, nullptr); 93 | class_registered_ = false; 94 | } 95 | 96 | Win32Window::Win32Window() { 97 | ++g_active_window_count; 98 | } 99 | 100 | Win32Window::~Win32Window() { 101 | --g_active_window_count; 102 | Destroy(); 103 | } 104 | 105 | bool Win32Window::CreateAndShow(const std::wstring& title, 106 | const Point& origin, 107 | const Size& size) { 108 | Destroy(); 109 | 110 | const wchar_t* window_class = 111 | WindowClassRegistrar::GetInstance()->GetWindowClass(); 112 | 113 | const POINT target_point = {static_cast(origin.x), 114 | static_cast(origin.y)}; 115 | HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); 116 | UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); 117 | double scale_factor = dpi / 96.0; 118 | 119 | HWND window = CreateWindow( 120 | window_class, title.c_str(), WS_OVERLAPPEDWINDOW | WS_VISIBLE, 121 | Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), 122 | Scale(size.width, scale_factor), Scale(size.height, scale_factor), 123 | nullptr, nullptr, GetModuleHandle(nullptr), this); 124 | 125 | if (!window) { 126 | return false; 127 | } 128 | 129 | return OnCreate(); 130 | } 131 | 132 | // static 133 | LRESULT CALLBACK Win32Window::WndProc(HWND const window, 134 | UINT const message, 135 | WPARAM const wparam, 136 | LPARAM const lparam) noexcept { 137 | if (message == WM_NCCREATE) { 138 | auto window_struct = reinterpret_cast(lparam); 139 | SetWindowLongPtr(window, GWLP_USERDATA, 140 | reinterpret_cast(window_struct->lpCreateParams)); 141 | 142 | auto that = static_cast(window_struct->lpCreateParams); 143 | EnableFullDpiSupportIfAvailable(window); 144 | that->window_handle_ = window; 145 | } else if (Win32Window* that = GetThisFromHandle(window)) { 146 | return that->MessageHandler(window, message, wparam, lparam); 147 | } 148 | 149 | return DefWindowProc(window, message, wparam, lparam); 150 | } 151 | 152 | LRESULT 153 | Win32Window::MessageHandler(HWND hwnd, 154 | UINT const message, 155 | WPARAM const wparam, 156 | LPARAM const lparam) noexcept { 157 | switch (message) { 158 | case WM_DESTROY: 159 | window_handle_ = nullptr; 160 | Destroy(); 161 | if (quit_on_close_) { 162 | PostQuitMessage(0); 163 | } 164 | return 0; 165 | 166 | case WM_DPICHANGED: { 167 | auto newRectSize = reinterpret_cast(lparam); 168 | LONG newWidth = newRectSize->right - newRectSize->left; 169 | LONG newHeight = newRectSize->bottom - newRectSize->top; 170 | 171 | SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, 172 | newHeight, SWP_NOZORDER | SWP_NOACTIVATE); 173 | 174 | return 0; 175 | } 176 | case WM_SIZE: { 177 | RECT rect = GetClientArea(); 178 | if (child_content_ != nullptr) { 179 | // Size and position the child window. 180 | MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, 181 | rect.bottom - rect.top, TRUE); 182 | } 183 | return 0; 184 | } 185 | 186 | case WM_ACTIVATE: 187 | if (child_content_ != nullptr) { 188 | SetFocus(child_content_); 189 | } 190 | return 0; 191 | } 192 | 193 | return DefWindowProc(window_handle_, message, wparam, lparam); 194 | } 195 | 196 | void Win32Window::Destroy() { 197 | OnDestroy(); 198 | 199 | if (window_handle_) { 200 | DestroyWindow(window_handle_); 201 | window_handle_ = nullptr; 202 | } 203 | if (g_active_window_count == 0) { 204 | WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); 205 | } 206 | } 207 | 208 | Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { 209 | return reinterpret_cast( 210 | GetWindowLongPtr(window, GWLP_USERDATA)); 211 | } 212 | 213 | void Win32Window::SetChildContent(HWND content) { 214 | child_content_ = content; 215 | SetParent(content, window_handle_); 216 | RECT frame = GetClientArea(); 217 | 218 | MoveWindow(content, frame.left, frame.top, frame.right - frame.left, 219 | frame.bottom - frame.top, true); 220 | 221 | SetFocus(child_content_); 222 | } 223 | 224 | RECT Win32Window::GetClientArea() { 225 | RECT frame; 226 | GetClientRect(window_handle_, &frame); 227 | return frame; 228 | } 229 | 230 | HWND Win32Window::GetHandle() { 231 | return window_handle_; 232 | } 233 | 234 | void Win32Window::SetQuitOnClose(bool quit_on_close) { 235 | quit_on_close_ = quit_on_close; 236 | } 237 | 238 | bool Win32Window::OnCreate() { 239 | // No-op; provided for subclasses. 240 | return true; 241 | } 242 | 243 | void Win32Window::OnDestroy() { 244 | // No-op; provided for subclasses. 245 | } 246 | --------------------------------------------------------------------------------