### Build Plugin Examples (Dart) Source: https://github.com/scerio/packages.flutter/blob/main/script/tool/README.md Builds example applications for a plugin, often generating an APK for Android. This is useful for testing the plugin's integration with example apps. ```sh cd dart run ./script/tool/bin/flutter_plugin_tools.dart build-examples --apk --packages plugin_name ``` -------------------------------- ### Basic Usage Example of epub_view in Flutter Source: https://github.com/scerio/packages.flutter/blob/main/packages/epub_view/README.md Demonstrates the fundamental setup of the EpubView widget. It includes initializing the EpubController with a document loaded from assets and displaying the document along with its table of contents and actual chapter title. ```dart import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:flutter_epub/flutter_epub.dart'; late EpubController _epubController; @override void initState() { super.initState(); _epubController = EpubController( // Load document document: EpubDocument.openAsset('assets/book.epub'), // Set start point epubCfi: 'epubcfi(/6/6[chapter-2]!/4/2/1612)', ); } @override Widget build(BuildContext context) => Scaffold( appBar: AppBar( // Show actual chapter name title: EpubViewActualChapter( controller: _epubController, builder: (chapterValue) => Text( 'Chapter: ' + (chapterValue?.chapter?.Title?.replaceAll('\n', '').trim() ?? ''), textAlign: TextAlign.start, ) ), ), // Show table of contents drawer: Drawer( child: EpubViewTableOfContents( controller: _epubController, ), ), // Show epub document body: EpubView( controller: _epubController, ), ); ``` -------------------------------- ### Flutter Full Explorer Example with File Upload Source: https://context7.com/scerio/packages.flutter/llms.txt Presents a comprehensive file explorer example in Flutter, utilizing the Explorer widget with a custom bottom bar and upload functionality. It configures the ExplorerController with a specific starting directory and implements an upload mechanism using the file_picker package. This snippet depends on 'explorer', 'explorer_io', and 'file_picker'. ```dart import 'package:explorer/explorer.dart'; import 'package:explorer/explorer_io.dart'; import 'package:flutter/material.dart'; import 'package:file_picker/file_picker.dart'; class FullExplorerExample extends StatefulWidget { @override _FullExplorerExampleState createState() => _FullExplorerExampleState(); } class _FullExplorerExampleState extends State { late ExplorerController _controller; @override void initState() { super.initState(); _controller = ExplorerController( provider: IoExplorerProvider(entryPath: '/storage/emulated/0/Documents'), ); } Future _uploadFiles() async { final result = await FilePicker.platform.pickFiles(allowMultiple: true); if (result != null) { for (var file in result.files) { print('Uploading: ${file.name}'); // Implement upload logic } } } @override Widget build(BuildContext context) { return Scaffold( body: Explorer( controller: _controller, builder: (context) => [ ExplorerToolbar(), ExplorerActionView(), Expanded(child: ExplorerFilesGridView()), ], bottomBarBuilder: (context) => Container( height: 50, color: Colors.grey[200], child: Center(child: Text('Bottom Bar')), ), uploadFiles: _uploadFiles, filePressed: (file) { showDialog( context: context, builder: (context) => AlertDialog( title: Text(file.name), content: Text('Size: ${file.size} bytes\nPath: ${file.path}'), actions: [ TextButton( onPressed: () => Navigator.pop(context), child: Text('Close'), ), ], ), ); }, ), ); } } ``` -------------------------------- ### Drive Plugin Examples (Dart) Source: https://github.com/scerio/packages.flutter/blob/main/script/tool/README.md Runs integration tests or drives example applications for a plugin on a specified platform (e.g., Android). The `--android` flag targets Android, and platforms can be omitted to see available options. ```sh cd dart run ./script/tool/bin/flutter_plugin_tools.dart drive-examples --android --packages plugin_name ``` -------------------------------- ### Update README.md from Example Sources (Dart) Source: https://github.com/scerio/packages.flutter/blob/main/script/tool/README.md Updates the README.md file of a plugin by extracting code snippets or documentation from its example sources. Requires submodules to be initialized and updated if they are used. ```sh cd dart run ./script/tool/bin/flutter_plugin_tools.dart update-excerpts --packages plugin_name ``` -------------------------------- ### CMake Installation Rules for Flutter Application Source: https://github.com/scerio/packages.flutter/blob/main/packages/pdfx/example/windows/CMakeLists.txt Defines how the application, its data, libraries, and assets are installed. It ensures that support files are placed next to the executable for in-place running and handles the re-copying of the assets directory to prevent stale files. ```cmake # === Installation === # Support files are copied into place next to the executable, so that it can # run in place. This is done instead of making a separate bundle (as on Linux) # so that building and running from within Visual Studio will work. set(BUILD_BUNDLE_DIR "$") # Make the "install" step default, as it's required to run. set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) if(PLUGIN_BUNDLED_LIBRARIES) install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() # Fully re-copy the assets directory on each build to avoid having stale files # from a previous install. set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) # Install the AOT library on non-Debug builds only. install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" CONFIGURATIONS Profile;Release COMPONENT Runtime) ``` -------------------------------- ### Activate Flutter Plugin Tools from Pub (Dart) Source: https://github.com/scerio/packages.flutter/blob/main/script/tool/README.md Installs the flutter_plugin_tools package globally using Dart's package manager. This makes the tool available for execution from any directory on the system. ```sh dart pub global activate flutter_plugin_tools ``` -------------------------------- ### Initialize ExplorerController with IoExplorerProvider Source: https://github.com/scerio/packages.flutter/blob/main/packages/explorer/README.md Shows how to initialize the ExplorerController using IoExplorerProvider for local file system navigation. This requires specifying an entry path for the explorer to start from. This provider is suitable for IO-based platforms and will not work on the web. ```dart _controller = ExplorerController( provider: IoExplorerProvider( entryPath: '/path/to/entry', // For IO explorer pass some entry path ), ) ``` -------------------------------- ### Assertion Examples for HexColor and HslColor in Dart Source: https://github.com/scerio/packages.flutter/blob/main/packages/flutter_color/README.md Provides assertion examples to verify the correct functionality of HexColor and HslColor constructors from the flutter_color package. These tests confirm that colors created using these classes are accurately represented by Flutter's native Color objects. ```dart // HexColor assert(HexColor('000000') == Color(0xFF000000)); assert(HexColor('#000000') == Color(0xFF000000)); assert(HexColor('FFFFFFFF') == Color(0xFFFFFFFF)); assert(HexColor('#B1000000') == Color(0xB1000000)); assert(HexColor('#B1000000').hexColor, '#B1000000'); // HslColor assert(HslColor(164, 100, 88) == Color(0xFFC2FFEF)); // HyzColor assert(XyzColor(0.1669, 0.2293, 0.0434) == Color(0xFF659027)); /// CielabColor assert(CielabColor(36.80, 55.20, -95.61) == Color(0xFF4832F7)); ``` -------------------------------- ### Flutter PDF Viewing with PDFx Source: https://github.com/scerio/packages.flutter/blob/main/packages/pdfx/README.md Example demonstrating how to use `PdfControllerPinch` and `PdfViewPinch` for high-quality zooming, and `PdfController` with `PdfView` for simpler display. Both controllers require a `PdfDocument` opened from an asset. Note that `PdfViewPinch` is not supported on Windows. ```dart import 'package:pdfx/pdfx.dart'; final pdfPinchController = PdfControllerPinch( document: PdfDocument.openAsset('assets/sample.pdf'), ); // Pdf view with re-render pdf texture on zoom (not loose quality on zoom) // Not supported on windows PdfViewPinch( controller: pdfPinchController, ); //-- or --// final pdfController = PdfController( document: PdfDocument.openAsset('assets/sample.pdf'), ); // Simple Pdf view with one render of page (loose quality on zoom) PdfView( controller: pdfController, ); ``` -------------------------------- ### Flutter Auto Animated List Example Source: https://github.com/scerio/packages.flutter/blob/main/packages/auto_animated/example/README.md Demonstrates the usage of `LiveList` from the `auto_animated` package to create a horizontally scrolling animated list. It includes configurations for item intervals, durations, padding, and a custom item builder for fade and slide transitions. This snippet requires the `auto_animated` Flutter package. ```dart import 'package:flutter/material.dart'; import 'package:auto_animated/auto_animated.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) => MaterialApp( home: Scaffold( backgroundColor: Colors.grey[100], appBar: AppBar( title: Text('Auto animated example'), leading: LiveIconButton( icon: AnimatedIcons.menu_close, firstTooltip: 'Menu', secondTooltip: 'Close', onPressed: () {}, ), ), body: Column( children: [ SizedBox( height: 200, child: LiveList( showItemInterval: Duration(milliseconds: 500), showItemDuration: Duration(seconds: 1), padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 24), scrollDirection: Axis.horizontal, itemCount: 10, itemBuilder: _buildAnimatedItem, ), ), ], ), ), ); /// Wrap Ui item with animation & padding Widget _buildAnimatedItem( BuildContext context, int index, Animation animation, ) => FadeTransition( opacity: Tween( begin: 0, end: 1, ).animate(animation), child: SlideTransition( position: Tween( begin: Offset(0, -0.1), end: Offset.zero, ).animate(animation), child: Padding( padding: EdgeInsets.only(right: 32), child: _buildCard(index.toString()), ), ), ); /// UI item for showing Widget _buildCard(String text) => Builder( builder: (context) => Container( width: 140, child: ClipRRect( borderRadius: BorderRadius.circular(4), child: Material( color: Colors.lime, child: Center( child: Text( text, style: Theme.of(context) .textTheme .display1 .copyWith(color: Colors.black), ), ), ), ), ), ); } ``` -------------------------------- ### Install PDFx Web Support Source: https://github.com/scerio/packages.flutter/blob/main/packages/pdfx/README.md This command integrates the necessary pdfjs library (via CDN) into your Flutter web project's `index.html` file. It's required for PDF rendering on the web. ```shell flutter pub run pdfx:install_web ``` -------------------------------- ### Color Creation and Manipulation Examples in Dart Source: https://github.com/scerio/packages.flutter/blob/main/packages/flutter_color/README.md Demonstrates various ways to create, convert, and manipulate colors using the flutter_color package. It shows how to initialize colors from different systems (Hex, HSL, XYZ, CIELAB), adjust their lightness/darkness, and mix them with other colors. This snippet covers core functionalities for color operations within a Flutter application. ```dart // Usage hex from string and alternative color systems HexColor('000000') // -> Color(0xFF000000) HslColor(164, 100, 88) // -> Color(0xFFC2FFEF) XyzColor(0.1669, 0.2293, 0.0434) // -> Color(0xFF659027) CielabColor(36.80, 55.20, -95.61) // -> Color(0xFF4832F7) // Make color darker or lighter Color(0xFF000000).lighter(100) // -> Color(0xFFFFFFFF) Color(0xFF000000).darker(50) // -> Color(0xFF808080) // Mix with other colors Color(0xFFFF0000).mix(Color(0xFF00FF00), .25) // -> Color(0xFFBF3F00) // Colors conversion Color.fromRGBO(255, 255, 255, 1).hexColor // -> '#FFFFFFFF' ``` -------------------------------- ### Flutter LiveIconButton Usage Source: https://github.com/scerio/packages.flutter/blob/main/packages/auto_animated/README.md Demonstrates the basic usage of the LiveIconButton widget, including simple icon display and an example with separate tooltips for different states or actions. ```dart // Simple LiveIconButton( icon: AnimatedIcons.arrow_menu, onPressed: () {}, ); // With separate tooltips LiveIconButton( icon: AnimatedIcons.arrow_menu, firstTooltip: 'Event', secondTooltip: 'Add', onPressed: () {}, ); ``` -------------------------------- ### Flutter File Explorer Screen with IoExplorerProvider Source: https://context7.com/scerio/packages.flutter/llms.txt Demonstrates creating a basic file explorer screen using the ExplorerController and IoExplorerProvider for local file system access. It initializes the controller with a starting path and defines a simple file press handler to show a message for large files. This snippet requires the 'explorer' and 'explorer_io' packages. ```dart import 'package:explorer/explorer.dart'; import 'package:explorer/explorer_io.dart'; import 'package:flutter/material.dart'; class FileExplorerScreen extends StatefulWidget { @override _FileExplorerScreenState createState() => _FileExplorerScreenState(); } class _FileExplorerScreenState extends State { late ExplorerController _controller; @override void initState() { super.initState(); _controller = ExplorerController( provider: IoExplorerProvider( entryPath: '/storage/emulated/0', ), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('File Explorer')), body: Explorer( controller: _controller, builder: (_) => [ ExplorerToolbar(), ExplorerActionView(), ExplorerFilesGridView(), ], filePressed: (file) { if (file.size > 200000) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('File too large: ${file.name}')), ); return; } print('Opening file: ${file.path}'); }, ), ); } @override void dispose() { _controller.dispose(); super.dispose(); } } ``` -------------------------------- ### Run Flutter Plugin Tools Globally (Dart) Source: https://github.com/scerio/packages.flutter/blob/main/script/tool/README.md Executes the globally installed flutter_plugin_tools. This command is used after activating the package globally via 'dart pub global activate'. Arguments are passed to control the tool's behavior. ```sh dart pub global run flutter_plugin_tools ``` -------------------------------- ### Controlling EPUB Document Navigation with epub_view Source: https://github.com/scerio/packages.flutter/blob/main/packages/epub_view/README.md Provides examples of how to interact with the EpubController to manage document navigation. This includes getting the current reading position as an 'epubCfi' string and navigating to a specific 'epubCfi'. ```dart // Get epub cfi string of actual view insets // for example output - epubcfi(/6/6[chapter-2]!/4/2/1612) final cfi = _epubController.generateEpubCfi(); // Navigate to paragraph in document _epubController.gotoEpubCfi('epubcfi(/6/6[chapter-2]!/4/2/1612)'); ``` -------------------------------- ### Install PDFx Windows Support Source: https://github.com/scerio/packages.flutter/blob/main/packages/pdfx/README.md This command automatically adds the required override for the pdfium version property in your project's `CMakeLists.txt` file. This is necessary for PDF rendering on Windows. ```shell flutter pub run pdfx:install_windows ``` -------------------------------- ### Install and Use Internet File for Network PDFs (Shell & Dart) Source: https://github.com/scerio/packages.flutter/blob/main/packages/pdfx/README.md This snippet shows how to add the `internet_file` package to your Flutter project and then use it to open a PDF document directly from a URL. The `InternetFile.get` method fetches the PDF data, which is then passed to `PdfDocument.openData`. ```shell flutter pub add internet_file ``` ```dart import 'package:internet_file/internet_file.dart'; PdfDocument.openData(InternetFile.get('https://github.com/ScerIO/packages.flutter/raw/fd0c92ac83ee355255acb306251b1adfeb2f2fd6/packages/native_pdf_renderer/example/assets/sample.pdf')) ``` -------------------------------- ### Color Lighten and Darken Operations in Dart Source: https://github.com/scerio/packages.flutter/blob/main/packages/flutter_color/README.md Illustrates how to lighten and darken colors using extension methods provided by the flutter_color package. The examples demonstrate adjusting the brightness of colors by a specified percentage, showing the resulting color values. ```dart // [black -> white] lighter by 100 percents assert(Color(0xFF000000).lighter(100), Color(0xFFFFFFFF)); // Another lighter example assert(Color.fromARGB(255, 64, 64, 64).lighter(50), Color.fromARGB(255, 192, 192, 192)); // [white -> grey] darker by 50 percents assert(Color(0xFF000000).darker(50), Color(0xFF808080)); // Another darker example assert(Color.fromARGB(255, 192, 192, 192).darker(25), Color.fromARGB(255, 128, 128, 128)); ``` -------------------------------- ### Dependency Installation for flutter_color Package Source: https://github.com/scerio/packages.flutter/blob/main/packages/flutter_color/README.md Shows how to add the flutter_color package as a dependency in a Flutter project's pubspec.yaml file. This is the standard method for including external libraries in Flutter development, enabling the use of its features. ```yaml dependencies: flutter_color: any ``` -------------------------------- ### Get PDF Document Progress and Page Info in Flutter Source: https://github.com/scerio/packages.flutter/blob/main/packages/pdfx/README.md Shows how to retrieve information about the PDF document being displayed, such as the current page number and the total number of pages. It also demonstrates how to get the document loading progress. ```dart // Actual showed page pdfController.page; // Count of all pages in document pdfController.pagesCount; // Get document progrees 0.0 - start, 1.0 - end _pdfController.documentProgress; ``` -------------------------------- ### Implement Custom REST API Storage Provider for Explorer Source: https://context7.com/scerio/packages.flutter/llms.txt Provides an example of a CustomRestApiProvider that implements the ExplorerProvider interface to interact with a RESTful API for file system operations. It handles listing directories, creating new directories and files, and removing or copying entries. Dependencies include the 'http' package for network requests and 'dart:convert' for JSON parsing. It takes an API base URL and an entry path as input. ```dart import 'package:explorer/explorer.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; class CustomRestApiProvider implements ExplorerProvider { final String apiBaseUrl; String _currentPath; CustomRestApiProvider({required String entryPath, required this.apiBaseUrl}) : _currentPath = entryPath; @override String get entryPath => '/'; @override String get currentPath => _currentPath; @override Future> go(String path) async { _currentPath = path; // Make API request to list directory contents final response = await http.get(Uri.parse('$apiBaseUrl/list?path=$path')); final data = json.decode(response.body); return (data['entries'] as List).map((item) { if (item['type'] == 'directory') { return ExplorerDirectory( name: item['name'], path: item['path'], ); } else { return ExplorerFile( name: item['name'], path: item['path'], size: item['size'], ); } }).toList(); } @override Future newDirectory(String name) async { final path = '$_currentPath/$name'; await http.post( Uri.parse('$apiBaseUrl/mkdir'), body: json.encode({'path': path}), ); return ExplorerDirectory(name: name, path: path); } @override Future newFile(String name) async { final path = '$_currentPath/$name'; await http.post( Uri.parse('$apiBaseUrl/touch'), body: json.encode({'path': path}), ); return ExplorerFile(name: name, path: path, size: 0); } @override Future remove(Entry entry) async { await http.delete( Uri.parse('$apiBaseUrl/remove'), body: json.encode({'path': entry.path}), ); } @override Future copy(Entry from, Entry to) async { await http.post( Uri.parse('$apiBaseUrl/copy'), body: json.encode({'from': from.path, 'to': to.path}), ); } } // Usage void useCustomProvider() { final controller = ExplorerController( provider: CustomRestApiProvider( entryPath: '/', apiBaseUrl: 'https://api.example.com/files', ), ); } ``` -------------------------------- ### CMake Build Configuration and Settings Source: https://github.com/scerio/packages.flutter/blob/main/packages/pdfx/example/windows/CMakeLists.txt Configures the minimum CMake version, project name, binary name, and installation path. It also manages build types (Debug, Profile, Release) based on whether the generator is multi-config. Standard compilation features and options are applied to targets. ```cmake cmake_minimum_required(VERSION 3.14) project(example LANGUAGES CXX) set(BINARY_NAME "example") cmake_policy(SET CMP0063 NEW) set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") # Configure build options. get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) if(IS_MULTICONFIG) set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" CACHE STRING "" FORCE) else() if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Flutter build mode" FORCE) set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Profile" "Release") endif() endif() set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") # Use Unicode for all projects. add_definitions(-DUNICODE -D_UNICODE) # Compilation settings that should be applied to most targets. function(APPLY_STANDARD_SETTINGS TARGET) target_compile_features(${TARGET} PUBLIC cxx_std_17) target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") target_compile_options(${TARGET} PRIVATE /EHsc) target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") target_compile_definitions(${TARGET} PRIVATE "<$:_DEBUG>") endfunction() ``` -------------------------------- ### Integrate UI Components for File Explorer Layout in Flutter Source: https://context7.com/scerio/packages.flutter/llms.txt Demonstrates how to use pre-built Explorer UI components like ExplorerToolbar, ExplorerActionView, and ExplorerFilesGridView to create a file explorer interface. It requires 'flutter/material.dart' and the 'explorer' package. This example sets up a basic column layout with a custom header, action view, and a scrollable grid of files, with a callback for file press events. ```dart import 'package:explorer/explorer.dart'; import 'package:explorer/explorer_io.dart'; import 'package:flutter/material.dart'; class CustomLayoutExplorer extends StatefulWidget { @override _CustomLayoutExplorerState createState() => _CustomLayoutExplorerState(); } class _CustomLayoutExplorerState extends State { late ExplorerController _controller; @override void initState() { super.initState(); _controller = ExplorerController( provider: IoExplorerProvider(entryPath: '/storage/emulated/0'), ); } @override Widget build(BuildContext context) { return Scaffold( body: Column( children: [ // Custom header with toolbar Container( color: Colors.blue, child: SafeArea( child: Explorer( controller: _controller, builder: (_) => [ExplorerToolbar()], ), ), ), // Action view for file operations Explorer( controller: _controller, builder: (_) => [ExplorerActionView()], ), // Main file grid Expanded( child: Explorer( controller: _controller, builder: (_) => [ Expanded(child: ExplorerFilesGridView()), ], filePressed: (file) { print('File: ${file.name}, Size: ${file.size}'); }, ), ), ], ), ); } } ``` -------------------------------- ### Custom Builders for Flutter PDF Viewers (General) Source: https://github.com/scerio/packages.flutter/blob/main/packages/pdfx/README.md This example shows how to customize the PdfView widget using custom builders, extending the functionality available in PdfViewPinch. It incorporates the `pageBuilder` for defining individual page display options, allowing for integration with pinch-to-zoom gestures and other visual enhancements through the PhotoView library. ```dart PdfView( controller: pdfController, builders: PdfViewBuilders( // All from `PdfViewPinch` and: pageBuilder: SomeWidget.pageBuilder, ), ); ``` -------------------------------- ### Control PDF Page Navigation in Flutter Source: https://github.com/scerio/packages.flutter/blob/main/packages/pdfx/README.md Provides examples of controlling page navigation within a PDF viewer using PdfController. This includes jumping to a specific page, animating page transitions, and moving to the next or previous page. ```dart // Jump to specified page pdfController.jumpTo(3); // Animate to specified page _pdfController.animateToPage(3, duration: Duration(milliseconds: 250), curve: Curves.ease); // Animate to next page _pdfController.nextPage(duration: Duration(milliseconds: 250), curve: Curves.easeIn); // Animate to previous page _pdfController.previousPage(duration: Duration(milliseconds: 250), curve: Curves.easeOut); ``` -------------------------------- ### Custom PDF Rendering Options in Flutter Source: https://github.com/scerio/packages.flutter/blob/main/packages/pdfx/README.md This example demonstrates how to customize the rendering of PDF pages using the PdfView widget's `renderer` property. You can control the output format (e.g., JPEG), resolution (by scaling width and height), and background color of the rendered page image. ```dart PdfView( controller: pdfController, renderer: (PdfPage page) => page.render( width: page.width * 2, height: page.height * 2, format: PdfPageImageFormat.jpeg, backgroundColor: '#FFFFFF', ), ); ``` -------------------------------- ### Set Up Flutter Plugin Tools from Source (Dart) Source: https://github.com/scerio/packages.flutter/blob/main/script/tool/README.md This command sets up the flutter_plugin_tools by fetching its dependencies. It requires navigating to the tool's directory within the repository and then returning to the root. This is primarily for direct development or contribution to the tools themselves. ```sh cd ./script/tool && dart pub get && cd ../../ ``` -------------------------------- ### Basic Explorer Widget Implementation in Flutter Source: https://github.com/scerio/packages.flutter/blob/main/packages/explorer/README.md Illustrates the basic implementation of the Explorer widget in Flutter. It takes an initialized ExplorerController and a builder function to define the UI components like the toolbar, action view, and file grid. It also shows how to handle file press events, including a size check. ```dart Explorer( controller: _controller, // Customize UI by Explorer & you own widgets! builder: (_) => [ ExplorerToolbar(), ExplorerActionView(), ExplorerFilesGridView(), ], // Callback called on file at explorer pressed filePressed: (file) { if (file.size > 200000) { final snackBar = SnackBar(content: Text('Can't open files with size > 200kb')); // Find the Scaffold in the widget tree and use it to show a SnackBar. ScaffoldMessenger.of(context).showSnackBar(snackBar); return; } } ) ``` -------------------------------- ### Add PDFx Dependency to Flutter Project Source: https://github.com/scerio/packages.flutter/blob/main/packages/pdfx/README.md This command adds the PDFx package as a dependency to your Flutter project. Ensure you have Flutter installed and configured. ```shell flutter pub add pdfx ``` -------------------------------- ### Get and Close PDF Document Page (Dart) Source: https://github.com/scerio/packages.flutter/blob/main/packages/pdfx/README.md Retrieves a specific page from an opened PDF document and includes the necessary step to close the document. Closing the document releases associated resources. ```dart final page = document.getPage(pageNumber); // Starts from 1 document.close(); ``` -------------------------------- ### Run Flutter Plugin Tools from Source (Dart) Source: https://github.com/scerio/packages.flutter/blob/main/script/tool/README.md Executes the flutter_plugin_tools script located in the ./script/tool directory. Arguments can be passed to specify which command to run and on which packages. This method is used when running directly from the repository source. ```sh dart run ./script/tool/bin/flutter_plugin_tools.dart ``` -------------------------------- ### CMake: Configure PDFium Download and Build Source: https://github.com/scerio/packages.flutter/blob/main/packages/pdfx/windows/CMakeLists.txt This CMake script sets up the build environment for the PDFx Flutter plugin. It determines the correct PDFium binary URL based on the version and architecture, downloads it, and then builds the plugin library by linking against PDFium and Flutter libraries. It also defines bundled libraries for distribution. ```cmake cmake_minimum_required(VERSION 3.15) set(PROJECT_NAME "pdfx") project(${PROJECT_NAME} LANGUAGES CXX) set(ARCH "x64") set(PDFIUM_VERSION "4690" CACHE STRING "Version of pdfium used") string(COMPARE GREATER_EQUAL ${PDFIUM_VERSION} "4690" PDFIUM_BINARY_NEW_FORMAT) if(${PDFIUM_VERSION} STREQUAL "latest") set(PDFIUM_URL "https://github.com/bblanchon/pdfium-binaries/releases/latest/download/pdfium-windows-${ARCH}.zip") elseif(PDFIUM_BINARY_NEW_FORMAT) set(PDFIUM_URL "https://github.com/bblanchon/pdfium-binaries/releases/download/chromium/${PDFIUM_VERSION}/pdfium-win-${ARCH}.tgz") else() set(PDFIUM_URL "https://github.com/bblanchon/pdfium-binaries/releases/download/chromium/${PDFIUM_VERSION}/pdfium-windows-${ARCH}.zip") endif() # Download pdfium include(../windows/DownloadProject.cmake) download_project( PROJ pdfium URL ${PDFIUM_URL} DOWNLOAD_EXTRACT_TIMESTAMP FALSE ) # This value is used when generating builds using this plugin, so it must # not be changed set(PLUGIN_NAME "pdfx_plugin") include(${pdfium_SOURCE_DIR}/PDFiumConfig.cmake) add_library(${PLUGIN_NAME} SHARED "pdfx.cpp" "pdfx.h" "pdfx_plugin.cpp" ) apply_standard_settings(${PLUGIN_NAME}) set_target_properties(${PLUGIN_NAME} PROPERTIES CXX_VISIBILITY_PRESET hidden) target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) target_include_directories(${PLUGIN_NAME} INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}/include") target_link_libraries(${PLUGIN_NAME} PRIVATE pdfium flutter flutter_wrapper_plugin) # List of absolute paths to libraries that should be bundled with the plugin set(pdfx_bundled_libraries "${PDFium_LIBRARY}" PARENT_SCOPE ) ``` -------------------------------- ### Publish Flutter Plugin Release (Shell) Source: https://github.com/scerio/packages.flutter/blob/main/script/tool/README.md This command uses the `flutter_plugin_tools.dart` script to publish a specific Flutter plugin. Ensure you are in the correct directory and have checked out the commit you wish to publish. The tool handles pushing tags and includes safety checks before executing `pub publish`. ```shell cd git checkout dart run ./script/tool/bin/flutter_plugin_tools.dart publish-plugin --packages ``` -------------------------------- ### Import Explorer Package in Flutter Source: https://github.com/scerio/packages.flutter/blob/main/packages/explorer/README.md Demonstrates how to import the main Explorer package and the IO-specific explorer provider for use in a Flutter project. Note that IoExplorerProvider is not compatible with web platforms. ```dart /// Main import import 'package:explorer/explorer.dart'; /// Import for [IoExplorerProvider]. /// Does work only IO (NOT WORK ON WEB) import 'package:explorer/explorer_io.dart'; ``` -------------------------------- ### Display EPUB Table of Contents with EpubViewTableOfContents - Flutter Source: https://context7.com/scerio/packages.flutter/llms.txt Integrates the EpubViewTableOfContents widget to display the table of contents for an EPUB document within a Flutter application. This is commonly used in navigation drawers for chapter selection. The example shows how to pass an EpubController to the widget. ```dart import 'package:epub_view/epub_view.dart'; import 'package:flutter/material.dart'; class EpubReaderWithToc extends StatelessWidget { final EpubController epubController; EpubReaderWithToc({required this.epubController}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('EPUB with TOC'), ), drawer: Drawer( child: Column( children: [ DrawerHeader( decoration: BoxDecoration(color: Colors.blue), child: Text( 'Table of Contents', style: TextStyle(color: Colors.white, fontSize: 24), ), ), Expanded( child: EpubViewTableOfContents( controller: epubController, ), ), ], ), ), body: EpubView(controller: epubController), ); } } ``` -------------------------------- ### ExplorerProvider Abstract Class Definition Source: https://github.com/scerio/packages.flutter/blob/main/packages/explorer/README.md Defines the abstract `ExplorerProvider` class, which outlines the interface for custom data providers. Implementing classes must define methods for navigating paths, creating directories and files, removing entries, and copying files or directories. ```dart abstract class ExplorerProvider { /// Explorer starts path String get entryPath; /// Explorer actual path String get currentPath; /// Navigate to specific path Future> go(String path); /// Create new directory at [currentPath] Future newDirectory(String name); /// Create new file at [currentPath] Future newFile(String name); /// Recursive remove file or dir at [currentPath] Future remove(Entry name); /// Copy file or dir Future copy(Entry from, Entry to); } ``` -------------------------------- ### CMake Build Configuration for Flutter Executable Source: https://github.com/scerio/packages.flutter/blob/main/packages/pdfx/example/windows/runner/CMakeLists.txt This snippet configures the CMAKE build system for a Flutter project. It defines the minimum required CMAKE version, project name, executable target, source files, and links necessary libraries like 'flutter' and 'flutter_wrapper_app'. It also sets compile definitions and include directories. ```cmake cmake_minimum_required(VERSION 3.14) project(runner LANGUAGES CXX) add_executable(${BINARY_NAME} WIN32 "flutter_window.cpp" "main.cpp" "utils.cpp" "win32_window.cpp" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" "Runner.rc" "runner.exe.manifest" ) apply_standard_settings(${BINARY_NAME}) target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") add_dependencies(${BINARY_NAME} flutter_assemble) ``` -------------------------------- ### Configure C++ Wrapper for Plugins (CMake) Source: https://github.com/scerio/packages.flutter/blob/main/packages/pdfx/example/windows/flutter/CMakeLists.txt This snippet sets up a static C++ library target for Flutter plugins. It defines core implementation sources, plugin-specific sources, applies standard build settings, and links against the main Flutter library. It also configures independent code and visibility. ```cmake # === Wrapper === list(APPEND CPP_WRAPPER_SOURCES_CORE "core_implementations.cc" "standard_codec.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/\n") list(APPEND CPP_WRAPPER_SOURCES_PLUGIN "plugin_registrar.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/\n") list(APPEND CPP_WRAPPER_SOURCES_APP "flutter_engine.cc" "flutter_view_controller.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/\n") # Wrapper sources needed for a plugin. add_library(flutter_wrapper_plugin STATIC ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} ) apply_standard_settings(flutter_wrapper_plugin) set_target_properties(flutter_wrapper_plugin PROPERTIES POSITION_INDEPENDENT_CODE ON) set_target_properties(flutter_wrapper_plugin PROPERTIES CXX_VISIBILITY_PRESET hidden) target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) target_include_directories(flutter_wrapper_plugin PUBLIC "${WRAPPER_ROOT}/include" ) add_dependencies(flutter_wrapper_plugin flutter_assemble) ``` -------------------------------- ### Opening EPUB Documents Locally with epub_view Source: https://github.com/scerio/packages.flutter/blob/main/packages/epub_view/README.md Illustrates different methods for opening EPUB documents stored locally on the device or within the app's assets. Note that `openFile` is not supported on the Web platform. ```dart EpubDocument.openAsset('assets/sample.pdf') EpubDocument.openData(FutureOr data) // Not supports on Web EpubDocument.openFile('path/to/file/on/device') ``` -------------------------------- ### Custom Builders for Flutter PDF Viewers (Pinch Zoom) Source: https://github.com/scerio/packages.flutter/blob/main/packages/pdfx/README.md This code demonstrates advanced customization for the PdfViewPinch widget using custom builders. It includes static methods for defining the main content builder (`builder`), a transition builder for animations (`transitionBuilder`), and a page builder for individual page options (`pageBuilder`). This allows for fine-grained control over loading indicators, error messages, and the visual presentation of pages, including pinch-to-zoom behavior. ```dart // Need static methods for builders arguments class SomeWidget { static Widget builder( BuildContext context, PdfViewPinchBuilders builders, PdfLoadingState state, WidgetBuilder loadedBuilder, PdfDocument? document, Exception? loadingError, ) { final Widget content = () { switch (state) { case PdfLoadingState.loading: return KeyedSubtree( key: const Key('pdfx.root.loading'), child: builders.documentLoaderBuilder?.call(context) ?? const SizedBox(), ); case PdfLoadingState.error: return KeyedSubtree( key: const Key('pdfx.root.error'), child: builders.errorBuilder?.call(context, loadingError!) ?? Center(child: Text(loadingError.toString())), ); case PdfLoadingState.success: return KeyedSubtree( key: Key('pdfx.root.success.${document!.id}'), child: loadedBuilder(context), ); } }(); final defaultBuilder = builders as PdfViewPinchBuilders; final options = defaultBuilder.options; return AnimatedSwitcher( duration: options.loaderSwitchDuration, transitionBuilder: options.transitionBuilder, child: content, ); } static Widget transitionBuilder(Widget child, Animation animation) => FadeTransition(opacity: animation, child: child); static PhotoViewGalleryPageOptions pageBuilder( BuildContext context, Future pageImage, int index, PdfDocument document, ) => PhotoViewGalleryPageOptions( imageProvider: PdfPageImageProvider( pageImage, index, document.id, ), minScale: PhotoViewComputedScale.contained * 1, maxScale: PhotoViewComputedScale.contained * 3.0, initialScale: PhotoViewComputedScale.contained * 1.0, heroAttributes: PhotoViewHeroAttributes(tag: '${document.id}-$index'), ); } PdfViewPinch( controller: pdfPinchController, builders: PdfViewPinchBuilders( options: const DefaultBuilderOptions( loaderSwitchDuration: const Duration(seconds: 1), transitionBuilder: SomeWidget.transitionBuilder, ), documentLoaderBuilder: (_) => const Center(child: CircularProgressIndicator()), pageLoaderBuilder: (_) => const Center(child: CircularProgressIndicator()), errorBuilder: (_, error) => Center(child: Text(error.toString())), builder: SomeWidget.builder, ), ) ``` -------------------------------- ### Run Dart Unit Tests (Dart) Source: https://github.com/scerio/packages.flutter/blob/main/script/tool/README.md Executes the Dart unit tests for a given plugin. This command helps ensure the correctness of individual units of code within the plugin. ```sh cd dart run ./script/tool/bin/flutter_plugin_tools.dart test --packages plugin_name ``` -------------------------------- ### Continuing Reading from Last Position with epub_view Source: https://github.com/scerio/packages.flutter/blob/main/packages/epub_view/README.md Shows how to initialize the EpubController to open an EPUB document at a specific position using an 'epubCfi' string. It also demonstrates how to retrieve the current 'epubCfi' and navigate to a specific 'epubCfi'. ```dart _epubController = EpubController( // initialize with epub cfi string for open book from last position epubCfi: 'epubcfi(/6/6[chapter-2]!/4/2/1612)', ); // Attach controller EpubView( controller: _epubController, ); // Get epub cfi string // for example output - epubcfi(/6/6[chapter-2]!/4/2/1612) final cfi = _epubController.generateEpubCfi(); // or usage controller for navigate _epubController.gotoEpubCfi('epubcfi(/6/6[chapter-2]!/4/2/1612)'); ``` -------------------------------- ### Analyze Plugin Code (Dart) Source: https://github.com/scerio/packages.flutter/blob/main/script/tool/README.md Runs the Dart static analyzer on the specified plugin to detect errors, warnings, and style issues. The `--packages` argument is used to select the target plugin(s). ```sh cd dart run ./script/tool/bin/flutter_plugin_tools.dart analyze --packages plugin_name ``` -------------------------------- ### Configure Flutter Library (CMake) Source: https://github.com/scerio/packages.flutter/blob/main/packages/pdfx/example/windows/flutter/CMakeLists.txt This snippet configures the Flutter library for the project. It includes setting paths for the DLL and ICU data file, defining header files, and creating an INTERFACE library target to manage include directories and linking against the Flutter library. ```cmake cmake_minimum_required(VERSION 3.14) set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") # Configuration provided via flutter tool. include(${EPHEMERAL_DIR}/generated_config.cmake) # TODO: Move the rest of this into files in ephemeral. See # https://github.com/flutter/flutter/issues/57146. set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") # === Flutter Library === set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") # Published to parent scope for install step. set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) list(APPEND FLUTTER_LIBRARY_HEADERS "flutter_export.h" "flutter_windows.h" "flutter_messenger.h" "flutter_plugin_registrar.h" "flutter_texture_registrar.h" ) list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") add_library(flutter INTERFACE) target_include_directories(flutter INTERFACE "${EPHEMERAL_DIR}" ) target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") add_dependencies(flutter flutter_assemble) ``` -------------------------------- ### Opening EPUB Documents from Network with epub_view Source: https://github.com/scerio/packages.flutter/blob/main/packages/epub_view/README.md Explains how to open EPUB documents directly from a network URL. This requires adding the 'internet_file' package and ensuring the server hosting the EPUB has CORS enabled. ```dart import 'package:internet_file/internet_file.dart'; // The cors policy is required on the server. // You can raise your cors proxy. EpubDocument.openData(InternetFile.get('https://link.to/book.epub')) ``` -------------------------------- ### Configure Flutter Tool Backend Assembly (CMake) Source: https://github.com/scerio/packages.flutter/blob/main/packages/pdfx/example/windows/flutter/CMakeLists.txt This snippet defines a custom command to invoke the Flutter tool backend for assembly. It uses a phony output file to ensure the command runs every time, as direct input/output tracking for the tool is not feasible. This command generates the Flutter library and associated headers. ```cmake # === Flutter tool backend === # _phony_ is a non-existent file to force this command to run every time, # since currently there's no way to get a full input/output list from the # flutter tool. set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) add_custom_command( OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} ${CPP_WRAPPER_SOURCES_APP} ${PHONY_OUTPUT} COMMAND ${CMAKE_COMMAND} -E env ${FLUTTER_TOOL_ENVIRONMENT} "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" windows-x64 $ VERBATIM ) add_custom_target(flutter_assemble DEPENDS "${FLUTTER_LIBRARY}" ${FLUTTER_LIBRARY_HEADERS} ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} ${CPP_WRAPPER_SOURCES_APP} ) ``` -------------------------------- ### Run Native Tests for Plugin (Shell) Source: https://github.com/scerio/packages.flutter/blob/main/script/tool/README.md Executes native tests (unit and/or integration) for a plugin on specified platforms like iOS or Android. Flags like `--ios`, `--android`, `--no-integration`, and `--no-unit` control which tests are run. ```sh cd # Run just unit tests for iOS and Android: dart run ./script/tool/bin/flutter_plugin_tools.dart native-test --ios --android --no-integration --packages plugin_name # Run all tests for macOS: dart run ./script/tool/bin/flutter_plugin_tools.dart native-test --macos --packages plugin_name ```