### Run Example App Source: https://github.com/deriv-com/flutter-chart/blob/master/CLAUDE.md Navigate to the example directory and run the example application on a connected device or emulator. ```bash cd example && flutter run ``` -------------------------------- ### Install Dependencies Source: https://github.com/deriv-com/flutter-chart/blob/master/CLAUDE.md Use this command to install all project dependencies. ```bash flutter pub get ``` -------------------------------- ### Build Example APK Source: https://github.com/deriv-com/flutter-chart/blob/master/CLAUDE.md Build an Android APK for the example app, targeting specified platforms and preserving icons. ```bash cd example && flutter build apk --target-platform android-arm,android-arm64,android-x64 --no-tree-shake-icons ``` -------------------------------- ### Line Chart Example Source: https://github.com/deriv-com/flutter-chart/blob/master/README.md Switch to a line chart by providing a LineSeries to the mainSeries parameter. This example assumes you have a list of Candle objects. ```dart Chart( mainSeries: LineSeries(candles), pipSize: 3, ); ``` -------------------------------- ### Setup Legacy Drawing Tools Source: https://github.com/deriv-com/flutter-chart/blob/master/doc/drawing_tools.md Initialize the legacy drawing tools by setting `useDrawingToolsV2` to `false` in the `Chart` widget. ```dart Chart( mainSeries: yourDataSeries, granularity: yourGranularity, drawingTools: DrawingTools(), // Initialize the drawing tools useDrawingToolsV2: false, // Set to false to use legacy implementation // other chart parameters... ) ``` -------------------------------- ### tokens.json Structure Example Source: https://github.com/deriv-com/flutter-chart/blob/master/lib/src/theme/design_tokens/README.md Illustrates the hierarchical structure for defining core and semantic design tokens in JSON format. Includes examples of solid colors and semantic theme definitions with references. ```json { "core/color/solid": { "core": { "color": { "solid": { "red": { "500": { "value": "#FF0000", "type": "color", "description": "Primary red color" } } } } } }, "semantic/theme/light": { "semantic": { "color": { "monochrome": { "surface": { "normal": { "lowest": { "value": "{core.color.opacity.black.75}", "type": "color" }, "low": { "value": "{core.color.opacity.black.100}", "type": "color" }, "midLow": { "value": "{core.color.opacity.black.200}", "type": "color" }, "midHigh": { "value": "{core.color.opacity.black.300}", "type": "color" }, "high": { "value": "{core.color.opacity.black.700}", "type": "color" }, "highest": { "value": "{core.color.opacity.black.800}", "type": "color" } }, "inverse": { "lowest": { "value": "{core.color.opacity.white.75}", "type": "color" }, "low": { "value": "{core.color.opacity.white.100}", "type": "color" }, "midLow": { "value": "{core.color.opacity.white.200}", "type": "color" }, "midHigh": { "value": "{core.color.opacity.white.300}", "type": "color" }, "high": { "value": "{core.color.opacity.white.700}", "type": "color" }, "highest": { "value": "{core.color.opacity.white.800}", "type": "color" } }, "static": { "blackLowest": { "value": "{core.color.opacity.black.75}", "type": "color" }, "blackLow": { "value": "{core.color.opacity.black.100}", "type": "color" }, "blackMidLow": { "value": "{core.color.opacity.black.200}", "type": "color" }, "blackMidHigh": { "value": "{core.color.opacity.black.300}", "type": "color" }, "blackHigh": { "value": "{core.color.opacity.black.700}", "type": "color" }, "blackHighest": { "value": "{core.color.opacity.black.800}", "type": "color" }, "whiteLowest": { "value": "{core.color.opacity.white.75}", "type": "color" }, "whiteLow": { "value": "{core.color.opacity.white.100}", "type": "color" }, "whiteMidLow": { "value": "{core.color.opacity.white.200}", "type": "color" }, "whiteMidHigh": { "value": "{core.color.opacity.white.300}", "type": "color" }, "whiteHigh": { "value": "{core.color.opacity.white.700}", "type": "color" }, "whiteHighest": { "value": "{core.color.opacity.white.800}", "type": "color" } } } } } } } } ``` -------------------------------- ### Setup Interactive Layer Drawing Tools (V2) for Desktop Source: https://github.com/deriv-com/flutter-chart/blob/master/doc/drawing_tools.md Enable the new drawing tools implementation by setting `useDrawingToolsV2` to `true` and specifying `InteractiveLayerDesktopBehaviour` for desktop platforms. ```dart Chart( mainSeries: yourDataSeries, granularity: yourGranularity, useDrawingToolsV2: true, // Enable the new drawing tools implementation interactiveLayerBehaviour: InteractiveLayerDesktopBehaviour(), // For desktop platforms // other chart parameters... ) ``` -------------------------------- ### Basic Candlestick Chart Example Source: https://github.com/deriv-com/flutter-chart/blob/master/README.md Demonstrates the simplest usage of the Chart widget by providing a CandleSeries. Ensure your Candle data is properly formatted. ```dart final candle1 = Candle( epoch: DateTime(...), high: 400, low: 50, open: 200, close: 100, ); final candle2 = Candle( epoch: DateTime(...), high: 500, low: 100, open: 100, close: 500, ); final candles = [candle1, candle2, ...] // Or provide your own data from a data source. ... Chart( mainSeries: CandleSeries(candles), pipSize: 3, // Number of decimal places when showing values on y-axis granularity: granularity, // Duration in milliseconds: for candles, this is the candle period; for ticks, this is the average time between ticks ); ``` -------------------------------- ### Dart Documentation Example for Indicator Offset Source: https://github.com/deriv-com/flutter-chart/blob/master/doc/contribution.md Illustrates how to document a class property, specifically the 'offset' for an indicator, including its purpose and a visual representation of its effect on data painting. ```dart ... /// The offset of this indicator. /// /// Indicator's data will be shifted by this number of tick while they are /// being painted. For example if we consider `*`s as indicator data on the /// chart below with default [offset] = 0: /// | /// | * (Tick3) (Tick4) * /// | (Tick1) * * /// | (Tick2) * /// -------------------------------------------> /// /// Indicator's data with [offset] = 1 will be like: /// | /// | * (Tick3) (Tick4) * /// | (Tick1) * * /// | (Tick2) * /// -------------------------------------------> /// final int offset; ... ``` -------------------------------- ### Setup Interactive Layer Drawing Tools (V2) for Mobile Source: https://github.com/deriv-com/flutter-chart/blob/master/doc/drawing_tools.md Enable the new drawing tools implementation by setting `useDrawingToolsV2` to `true` and specifying `InteractiveLayerMobileBehaviour` for mobile applications, which is optimized for touch interactions. ```dart Chart( mainSeries: yourDataSeries, granularity: yourGranularity, useDrawingToolsV2: true, interactiveLayerBehaviour: InteractiveLayerMobileBehaviour(), // Optimized for touch interactions // other chart parameters... ) ``` -------------------------------- ### Convert Basic Markers to Grouped Markers Source: https://github.com/deriv-com/flutter-chart/blob/master/doc/chart_markers_revamp_migration.md This example demonstrates how to convert basic markers into grouped markers, including contract circles, P/L labels, and associated properties. Ensure `currentEpoch` and `profitAndLossText` are provided for `MarkerGroup`. ```dart // Convert your basic markers to grouped markers with contract circle and P/L label List buildGroups(List markers, int nowEpoch) { return markers.map((m) { final endEpoch = m.epoch + 3000; // your duration final parts = [ ChartMarker(epoch: m.epoch, quote: m.quote, direction: m.direction, markerType: MarkerType.entrySpot), ChartMarker(epoch: endEpoch, quote: m.quote, direction: m.direction, markerType: MarkerType.exitTime), ChartMarker( epoch: m.epoch, quote: m.quote, direction: m.direction, markerType: MarkerType.contractMarker, onTap: () { /* toggle active */ }, ), ]; // Optionally show P/L label parts.add( ChartMarker( epoch: endEpoch, quote: m.quote, direction: m.direction, markerType: MarkerType.profitAndLossLabel, ), ); return MarkerGroup( parts, type: 'tick', direction: m.direction, id: 'group_${m.epoch}', currentEpoch: nowEpoch, profitAndLossText: '+9.55 USD', props: const MarkerProps( isProfit: true, isRunning: false, contractMarkerLeftPadding: 16, ), onTap: () { /* open details */ }, ); }).toList(); } ``` -------------------------------- ### Complete Interactive Layer Example with Controller Source: https://github.com/deriv-com/flutter-chart/blob/master/doc/interactive_layer_usage.md A complete Flutter widget demonstrating the integration of the Interactive Layer V2 with a controller. It initializes platform-specific behaviors and includes a UI element to cancel drawing tool additions. ```dart class ChartWithInteractiveLayer extends StatefulWidget { @override _ChartWithInteractiveLayerState createState() => _ChartWithInteractiveLayerState(); } class _ChartWithInteractiveLayerState extends State { final InteractiveLayerController _interactiveLayerController = InteractiveLayerController(); late final InteractiveLayerBehaviour _interactiveLayerBehaviour; @override void initState() { super.initState(); // Create the appropriate behavior based on platform with controller _interactiveLayerBehaviour = kIsWeb ? InteractiveLayerDesktopBehaviour( controller: _interactiveLayerController) : InteractiveLayerMobileBehaviour( controller: _interactiveLayerController); } @override Widget build(BuildContext context) { return Stack( children: [ DerivChart( useDrawingToolsV2: true, interactiveLayerBehaviour: _interactiveLayerBehaviour, mainSeries: CandleSeries(candles), granularity: 60000, activeSymbol: 'R_100', pipSize: 4, // Other chart parameters... ), // UI to show a cancel button when adding a drawing tool Positioned( top: 16, right: 16, child: ListenableBuilder( listenable: _interactiveLayerController, builder: (_, __) { if (_interactiveLayerController.currentState is InteractiveAddingToolState) { return Row( mainAxisSize: MainAxisSize.min, children: [ const Text('Cancel adding'), IconButton( onPressed: _interactiveLayerController.cancelAdding, icon: const Icon(Icons.cancel), ), ], ); } return const SizedBox(); }, ), ), ], ); } } ``` -------------------------------- ### Configure Overlay and Bottom Technical Indicators Source: https://github.com/deriv-com/flutter-chart/blob/master/README.md Integrate multiple technical indicators into the chart using `overlayConfigs` for indicators sharing the main y-axis and `bottomConfigs` for indicators with a separate y-axis. This example includes Bollinger Bands, SMI, and RSI. ```dart Chart( mainSeries: CandleSeries(candles), overlayConfigs: [ // Bollinger Bands BollingerBandsIndicatorConfig( period: 20, standardDeviation: 2, movingAverageType: MovingAverageType.exponential, upperLineStyle: LineStyle(color: Colors.purple), middleLineStyle: LineStyle(color: Colors.black), lowerLineStyle: LineStyle(color: Colors.blue), ), ], // Bottom indicators with separate scale bottomConfigs: [ SMIIndicatorConfig( period: 14, signalPeriod: 9, lineStyle: LineStyle(color: Colors.blue, thickness: 2), signalLineStyle: LineStyle(color: Colors.red), ), // Relative Strength Index (RSI) RSIIndicatorConfig( period: 14, lineStyle: LineStyle( color: Colors.green, thickness: 1, ), oscillatorLinesConfig: OscillatorLinesConfig( overboughtValue: 70, oversoldValue: 30, overboughtStyle: LineStyle(color: Colors.red), oversoldStyle: LineStyle(color: Colors.green), ), showZones: true, ), SMIIndicatorConfig(period: 10, lineStyle: LineStyle(color: Colors.green)) ], pipSize: 3, granularity: 60, // 1 minute candles ); ``` -------------------------------- ### Listen to Crosshair Appearance Source: https://github.com/deriv-com/flutter-chart/blob/master/README.md Utilize the `onCrosshairAppeared` callback to trigger actions when the chart's crosshair becomes visible. This example demonstrates triggering a vibration. ```dart Chart( mainSeries: LineSeries(candles), pipSize: 4, onCrosshairAppeared: () => Vibration.vibrate(duration: 50), ); ``` -------------------------------- ### Handle Taps for Active Markers and Groups Source: https://github.com/deriv-com/flutter-chart/blob/master/doc/chart_markers_revamp_migration.md Implement `onTap` and `onTapOutside` handlers for `ActiveMarkerGroup` to manage active states. This example shows clearing the active group when tapping outside. ```dart _activeMarkerGroup = ActiveMarkerGroup( markers: markers, type: 'tick', direction: MarkerDirection.up, // or MarkerDirection.down id: id, currentEpoch: nowEpoch, onTap: () => openContract(id), onTapOutside: () => setState(() => _activeMarkerGroup = null), ); ``` -------------------------------- ### Add Collapsed Time Markers to Chart Source: https://github.com/deriv-com/flutter-chart/blob/master/doc/chart_markers_revamp_migration.md Use `startTimeCollapsed` and `exitTimeCollapsed` for minimal time markers in compact contexts. This example shows adding these alongside `entrySpot` markers. ```dart chartMarkers.addAll([ ChartMarker( epoch: startTimeEpoch, // slight lead for visual clarity quote: startQuote, direction: direction, markerType: MarkerType.startTimeCollapsed, ), ChartMarker( epoch: entrySpotEpoch, quote: startQuote, direction: direction, markerType: MarkerType.entrySpot, ), ChartMarker( epoch: exitTimeEpoch, quote: startQuote, direction: direction, markerType: MarkerType.exitTimeCollapsed, ), ]); ``` -------------------------------- ### Initialize AddOnsRepository for Indicators Source: https://github.com/deriv-com/flutter-chart/blob/master/doc/deriv_chart_widget_usage.md Create an instance of AddOnsRepository to manage indicator configurations. This is useful for custom interfaces where you need to handle indicator creation from saved data and define edit callbacks. ```Dart _indicatorsRepo = AddOnsRepository( // Is called when fetching the saved indicators from the shared preferences. // To handle how an IndicatorConfig object should be created from a saved JSON object. createAddOn: (Map map) => IndicatorConfig.fromJson(map), onEditCallback: (int index) { // handle edit of an indicator on index from _indicatorsRepo.items }, // A string acts as a key for the set of indicators that are saved. so we can have a separate set of saved indicators per key // For example we can have saved indicators per symbol if we pass the symbol code every time it changes to the indicator repo. sharedPrefKey: 'R_100', ); ``` -------------------------------- ### Run All Tests Source: https://github.com/deriv-com/flutter-chart/blob/master/CLAUDE.md Execute all unit and widget tests for the project. ```bash flutter test ``` -------------------------------- ### Style Horizontal Barrier Annotation Source: https://github.com/deriv-com/flutter-chart/blob/master/README.md Customize the appearance of a HorizontalBarrier annotation by providing a custom style. This example sets a specific color and disables dashed lines. ```dart HorizontalBarrier( ... style: HorizontalBarrierStyle( color: const Color(0xFF00A79E), isDashed: false, ), visibility: HorizontalBarrierVisibility.forceToStayOnRange, ) ``` -------------------------------- ### Dynamic Platform Detection for Behavior Source: https://github.com/deriv-com/flutter-chart/blob/master/doc/interactive_layer_usage.md Instantiate behaviors dynamically based on the platform using `kIsWeb` for automatic selection of appropriate interaction modes. ```dart // Dynamic platform-based behavior selection final InteractiveLayerBehaviour behaviour = kIsWeb ? InteractiveLayerDesktopBehaviour() // For web/desktop : InteractiveLayerMobileBehaviour(); // For mobile Chart( useDrawingToolsV2: true, interactiveLayerBehaviour: behaviour, mainSeries: CandleSeries(candles), // Other parameters... ) ``` -------------------------------- ### Run Static Analysis Source: https://github.com/deriv-com/flutter-chart/blob/master/CLAUDE.md Execute static analysis to check for potential issues in the code. Use --no-fatal-infos to include informational messages. ```bash flutter analyze --no-fatal-infos ``` -------------------------------- ### Generate Design Token Files (Bash) Source: https://github.com/deriv-com/flutter-chart/blob/master/lib/src/theme/design_tokens/README.md Executes a script to generate, format, and analyze design token files. This is the recommended method for updating token files. ```bash bash scripts/generate_and_check_token_files.sh ``` -------------------------------- ### Instantiate XAxisModel with Snap Markers Source: https://github.com/deriv-com/flutter-chart/blob/master/doc/chart_markers_revamp_migration.md When instantiating `XAxisModel` directly, provide the `snapMarkersToIntervals` flag. ```dart final xAxis = XAxisModel( entries: ticks, granularity: granularityMs, animationController: controller, isLive: true, snapMarkersToIntervals: true, maxCurrentTickOffset: 150, ); ``` -------------------------------- ### Widget Hierarchy Overview Source: https://github.com/deriv-com/flutter-chart/blob/master/CLAUDE.md Illustrates the layered architecture of the chart components, from platform-specific axes to core visualization coordinators. ```plaintext XAxisWrapper (platform-specific X-axis, data management, zoom/scroll) └── GestureManager (user interactions: pan, zoom, tap) └── Chart (visualization coordinator) ├── MainChart (primary chart: candles, overlays, crosshair, drawings) └── BottomCharts (indicators with separate Y-axis: RSI, MACD, etc.) ``` -------------------------------- ### Check Code Formatting Source: https://github.com/deriv-com/flutter-chart/blob/master/CLAUDE.md Verify if the code adheres to the project's formatting standards. This command exits with a non-zero status if formatting changes are needed. ```bash dart format --set-exit-if-changed . ``` -------------------------------- ### Generate Design Token Files (Dart) Source: https://github.com/deriv-com/flutter-chart/blob/master/lib/src/theme/design_tokens/README.md Directly runs the Dart script to parse tokens and generate the corresponding Dart files. ```dart dart lib/src/theme/design_tokens/design_token_parser.dart ``` -------------------------------- ### Integrate AddOnsRepository with DerivChart Source: https://github.com/deriv-com/flutter-chart/blob/master/doc/deriv_chart_widget_usage.md Pass the initialized AddOnsRepository instance to the DerivChart widget to enable indicator management. ```Dart DerivChart( indicatorsRepo: _indicatorsRepo, ... ... ) ``` -------------------------------- ### Run Dart Analyzer and Unit Tests Source: https://github.com/deriv-com/flutter-chart/blob/master/doc/contribution.md Before submitting a Pull Request, ensure these commands run locally without warnings or issues to check for Dart static analyzer errors and run unit tests. ```bash flutter analyze ``` ```bash flutter test ``` -------------------------------- ### Custom Platform Behavior Logic Source: https://github.com/deriv-com/flutter-chart/blob/master/doc/interactive_layer_usage.md Implement sophisticated platform detection logic, such as forcing mobile behavior on tablets even when running on the web, by checking device characteristics. ```dart // Example: Force mobile behavior on tablets even if on web final bool isMobileEnvironment = Platform.isAndroid || Platform.isIOS || (kIsWeb && MediaQuery.of(context).size.width < 768); final InteractiveLayerBehaviour behaviour = isMobileEnvironment ? InteractiveLayerMobileBehaviour() : InteractiveLayerDesktopBehaviour(); DerivChart( useDrawingToolsV2: true, interactiveLayerBehaviour: behaviour, mainSeries: CandleSeries(candles), ) ``` -------------------------------- ### Load Saved Indicators from SharedPreferences Source: https://github.com/deriv-com/flutter-chart/blob/master/doc/deriv_chart_widget_usage.md Load previously saved indicators into the AddOnsRepository using a shared preferences instance and a specific key. This method should be called after initializing the repository. ```Dart _indicatorsRepo.loadFromPrefs( await SharedPreferences.getInstance(), 'R_100', ); ``` -------------------------------- ### Format Code Source: https://github.com/deriv-com/flutter-chart/blob/master/CLAUDE.md Apply code formatting to the entire project according to Dart standards. ```bash dart format . ``` -------------------------------- ### Initialize ChartController Source: https://github.com/deriv-com/flutter-chart/blob/master/README.md A `ChartController` can be provided to the `Chart` widget to programmatically control scrolling and scaling. Instantiate the controller and pass it to the `Chart`'s `controller` property. ```dart final ChartController _controller = ChartController(); .... Chart( ... controller: _controller, ... ) _controller.scrollToLastTick(); _controller.scale(100); ``` -------------------------------- ### Custom Chart Theme Source: https://github.com/deriv-com/flutter-chart/blob/master/README.md Create a custom theme by extending `ChartDefaultDarkTheme` or `ChartDefaultLightTheme` and overriding specific properties like `gridStyle` to customize the chart's appearance. ```dart class CustomTheme extends ChartDefaultDarkTheme { @override GridStyle get gridStyle => GridStyle( gridLineColor: Colors.yellow, xLabelStyle: textStyle( textStyle: caption2, color: Colors.yellow, fontSize: 13, ), ); } ``` ```dart Chart( ... theme: customTheme /*instance of your custom theme*/, ... ) ``` -------------------------------- ### Design Token Configuration Source: https://github.com/deriv-com/flutter-chart/blob/master/lib/src/theme/design_tokens/README.md Defines categories, output paths, class names, and token names for generating Dart design token files. ```json { "tokenCategories": { "core": { "outputPath": "lib/src/theme/design_tokens/core_design_tokens.dart", "className": "CoreDesignTokens", "tokenNames": [ "core/border", "core/color/solid", "core/color/opacity", "core/color/gradients", "core/boxShadow", "core/opacity", "core/spacing", "core/typography", "core/motion", "core/sizing", "semantic/global", "semantic/viewPort/default" ] }, "light": { "outputPath": "lib/src/theme/design_tokens/light_theme_design_tokens.dart", "className": "LightThemeDesignTokens", "tokenNames": ["semantic/theme/light"] }, "dark": { "outputPath": "lib/src/theme/design_tokens/dark_theme_design_tokens.dart", "className": "DarkThemeDesignTokens", "tokenNames": ["semantic/theme/dark"] }, "component": { "outputPath": "lib/src/theme/design_tokens/component_design_tokens.dart", "className": "ComponentDesignTokens", "tokenNames": ["component/component"] } } } ``` -------------------------------- ### Initialize DerivChart Source: https://github.com/deriv-com/flutter-chart/blob/master/README.md Use `DerivChart` as a wrapper around the `Chart` widget to manage indicators and save/restore selected ones. Properties like `mainSeries`, `granularity`, `activeSymbol`, and `pipSize` are essential for its initialization. ```dart DerivChart( mainSeries: CandleSeries(candles), granularity: 60, // 60 seconds activeSymbol: 'default', pipSize: 4, ) ``` -------------------------------- ### Show Entry and Exit Tick Markers Source: https://github.com/deriv-com/flutter-chart/blob/master/README.md Configure `entryTick` and `exitTick` within `markerSeries` to display specific tick markers on the chart. ```dart Chart( ..., markerSeries: MarkerSeries( [...], entryTick: Tick(epoch: ..., quote: ...), exitTick: Tick(epoch: ..., quote: ...), ), ``` -------------------------------- ### Run Code Generation Source: https://github.com/deriv-com/flutter-chart/blob/master/CLAUDE.md Execute code generation tasks, such as for JSON serialization. --delete-conflicting-outputs ensures old generated files are removed. ```bash dart run build_runner build --delete-conflicting-outputs ``` -------------------------------- ### Import Generated Design Token Files Source: https://github.com/deriv-com/flutter-chart/blob/master/lib/src/theme/design_tokens/README.md Import the necessary generated design token files into your Flutter application. ```dart import 'package:deriv_chart/src/theme/design_tokens/core_design_tokens.dart'; import 'package:deriv_chart/src/theme/design_tokens/light_theme_design_tokens.dart'; import 'package:deriv_chart/src/theme/design_tokens/dark_theme_design_tokens.dart'; import 'package:deriv_chart/src/theme/design_tokens/component_design_tokens.dart'; ``` -------------------------------- ### Handle Contract Marker Taps Source: https://github.com/deriv-com/flutter-chart/blob/master/doc/chart_markers_revamp_migration.md Provide an `onTap` callback when constructing a `ChartMarker` of type `contractMarker` to handle taps on the contract circle. ```dart ChartMarker( epoch: startEpoch, quote: startQuote, direction: MarkerDirection.up, markerType: MarkerType.contractMarker, onTap: () { /* open contract details */ }, ); ``` -------------------------------- ### Show Markers on Chart Source: https://github.com/deriv-com/flutter-chart/blob/master/README.md Supply `markerSeries` to display markers on the chart. Each marker can have an `onTap` callback. ```dart Chart( ..., markerSeries: MarkerSeries([ Marker.up(epoch: 123, quote: 10, onTap: () {}), Marker.down(epoch: 124, quote: 12, onTap: () {}), ]), ); ``` -------------------------------- ### Immutable Model Classes Source: https://github.com/deriv-com/flutter-chart/blob/master/CLAUDE.md Demonstrates the use of the @immutable annotation and const constructors for creating immutable model classes in Dart. This promotes predictability and performance. ```dart @immutable class MyModel { final String data; const MyModel(this.data); } ``` -------------------------------- ### Configure Design Token Logger Verbosity Source: https://github.com/deriv-com/flutter-chart/blob/master/lib/src/theme/design_tokens/README.md Adjust the log level to control the verbosity of the output. Options include error, debug, and none. ```dart DesignTokenLogger.logLevel = LogLevel.error; ``` ```dart DesignTokenLogger.logLevel = LogLevel.debug; ``` ```dart DesignTokenLogger.logLevel = LogLevel.none; ``` -------------------------------- ### Populate MarkerGroup Props Source: https://github.com/deriv-com/flutter-chart/blob/master/doc/chart_markers_revamp_migration.md Populate `MarkerGroup.props` with `MarkerProps` to control styling for lines, circle fill/border, and optional labels within the contract circle. ```dart MarkerGroup( markers, type: 'tick', direction: MarkerDirection.up, // or MarkerDirection.down props: MarkerProps( isProfit: true, // or false isRunning: false, // false when contract is closed markerLabel: 'NT', // optional; otherwise arrow is shown contractMarkerLeftPadding: 16, // horizontal padding from left edge ), ); ``` -------------------------------- ### Custom Interactive Layer Behavior Source: https://github.com/deriv-com/flutter-chart/blob/master/doc/drawing_tools.md Create a custom implementation of `InteractiveLayerBehaviour` by extending the class and overriding its methods to tailor the drawing tools experience. ```dart import 'package:deriv_chart/deriv_chart.dart'; class CustomInteractiveLayerBehaviour extends InteractiveLayerBehaviour { // Override to customize behavior } // In your widget build method Chart( mainSeries: yourDataSeries, granularity: yourGranularity, useDrawingToolsV2: true, interactiveLayerBehaviour: CustomInteractiveLayerBehaviour(), // other chart parameters... ) ``` -------------------------------- ### Add a New Indicator Source: https://github.com/deriv-com/flutter-chart/blob/master/doc/deriv_chart_widget_usage.md Add a new indicator to the repository using its configuration object. This will update the chart with the new indicator. ```Dart _indicatorRepo.add(MACDIndicatorConfig()); ``` -------------------------------- ### ColorUtils Utility Functions Source: https://github.com/deriv-com/flutter-chart/blob/master/showcase_app/lib/widgets/README.md Utilize ColorUtils for theme-aware color presets, contrast calculations, accessibility checks, and color name identification. ```dart // Get theme-aware color presets final isDarkTheme = Theme.of(context).brightness == Brightness.dark; final themeColors = ColorUtils.getThemeColors(isDarkTheme); // Get bullish/bearish color presets final bullishColors = ColorUtils.getBullishColors(); final bearishColors = ColorUtils.getBearishColors(); // Check contrast for accessibility final contrastInfo = ColorUtils.checkContrast(foregroundColor, backgroundColor); final isAccessible = contrastInfo['normalText']; // true if contrast ratio >= 4.5:1 // Get color name final colorName = ColorUtils.getColorName(myColor); ``` -------------------------------- ### Listen to Controller State Changes Source: https://github.com/deriv-com/flutter-chart/blob/master/doc/interactive_layer_usage.md Listen to controller state changes to display user guidance or UI elements. This is useful for providing feedback during interactive operations like adding drawing tools. ```dart ListenableBuilder( listenable: controller, builder: (context, _) { if (controller.currentState is InteractiveAddingToolState) { return Column( children: [ Text('Currently adding a drawing tool'), Text('Tap on the chart to place the tool'), ElevatedButton( onPressed: controller.cancelAdding, child: Text('Cancel'), ), ], ); } return SizedBox(); }, ) ``` -------------------------------- ### Import Deriv Chart Package Source: https://github.com/deriv-com/flutter-chart/blob/master/doc/drawing_tools.md This import statement is required for both legacy and interactive layer drawing tools. ```dart import 'package:deriv_chart/deriv_chart.dart'; ``` -------------------------------- ### Enable Interactive Layer V2 in DerivChart Source: https://github.com/deriv-com/flutter-chart/blob/master/doc/interactive_layer_usage.md Set the `useDrawingToolsV2` flag to `true` to enable the new interactive layer for drawing tools. This is the primary step for activating the feature. ```dart DerivChart( useDrawingToolsV2: true, // Enable Interactive Layer V2 mainSeries: CandleSeries(candles), granularity: 60000, activeSymbol: 'R_100', pipSize: 4, drawingToolsRepo: myDrawingToolsRepo, // Optional ) ``` -------------------------------- ### DerivColorPicker with Chart Themes Source: https://github.com/deriv-com/flutter-chart/blob/master/showcase_app/lib/widgets/README.md Integrate DerivColorPicker with chart themes to customize elements like bullish/bearish candle colors. Use predefined color presets from ColorUtils. ```dart DerivColorPicker( label: 'Bullish Color:', selectedColor: _bullishColor, onColorChanged: (color) { setState(() { _bullishColor = color; // Update the chart theme _chartTheme = CustomDarkTheme( customBullishColor: _bullishColor, // other properties... ); }); }, // Use predefined bullish color presets presetColors: ColorUtils.getBullishColors(), ) ``` -------------------------------- ### Customize Interactive Layer Behavior Source: https://github.com/deriv-com/flutter-chart/blob/master/doc/interactive_layer_usage.md You can specify `InteractiveLayerMobileBehaviour` for touch or `InteractiveLayerDesktopBehaviour` for mouse/keyboard interactions by passing the `interactiveLayerBehaviour` parameter. ```dart // Mobile behavior - optimized for touch interactions final InteractiveLayerBehaviour mobileBehaviour = InteractiveLayerMobileBehaviour(); // Desktop behavior - optimized for mouse and keyboard interactions final InteractiveLayerBehaviour desktopBehaviour = InteractiveLayerDesktopBehaviour(); Chart( useDrawingToolsV2: true, interactiveLayerBehaviour: mobileBehaviour, // or desktopBehaviour mainSeries: CandleSeries(candles), // Other parameters... ) ``` -------------------------------- ### Configure Chart Snap Markers to Intervals Source: https://github.com/deriv-com/flutter-chart/blob/master/doc/chart_markers_revamp_migration.md Set `snapMarkersToIntervals` in `ChartConfig` to align markers to candle centerlines. The default is true. ```dart final chartConfig = ChartConfig( granularity: granularityMs, snapMarkersToIntervals: true, // default is true; set explicitly if you manage config ); ``` -------------------------------- ### Embed MarkerArea with AnimationInfo Source: https://github.com/deriv-com/flutter-chart/blob/master/doc/chart_markers_revamp_migration.md Pass `AnimationInfo` to `MarkerArea` to ensure smooth animations and consistent chart behavior. The `currentTickPercent` can be bound to your animation driver. ```dart MarkerArea( markerSeries: series, quoteToCanvasY: quoteToCanvasY, animationInfo: const AnimationInfo( currentTickPercent: 0.0, // or bind to your animation driver ), ); ``` -------------------------------- ### Add Tick Indicator Annotation Source: https://github.com/deriv-com/flutter-chart/blob/master/README.md Demonstrates how to add a TickIndicator annotation to the chart to display a tick mark at a specific data point. Ensure the `candles` data is properly formatted. ```dart Chart( mainSeries: LineSeries(candles), pipSize: 3, annotations: [ TickIndicator(candles.last), ], ); ``` -------------------------------- ### Show DerivColorPickerDialog Source: https://github.com/deriv-com/flutter-chart/blob/master/showcase_app/lib/widgets/README.md Use showDerivColorPickerDialog to present an advanced color picker dialog. It supports RGB sliders, hex input, and color palettes. ```dart final color = await showDerivColorPickerDialog( context, initialColor: Colors.blue, title: 'Select Text Color', ); if (color != null) { // Use the selected color setState(() { _textColor = color; }); } ``` -------------------------------- ### Styling CandleSeries Source: https://github.com/deriv-com/flutter-chart/blob/master/README.md Customize the appearance of CandleSeries by providing a CandleStyle object to the style parameter. This allows setting positive and negative colors. ```dart Chart( mainSeries: CandleSeries( candles, style: CandleStyle( positiveColor: Colors.green, negativeColor: Colors.red ), ), ... ); ``` -------------------------------- ### Provide Prominent Colors in Custom MarkerStyle Source: https://github.com/deriv-com/flutter-chart/blob/master/doc/chart_markers_revamp_migration.md Use this to define prominent colors for entry/exit spot circles and connector lines in your custom theme's MarkerStyle to improve contrast. ```dart const MarkerStyle( upColorProminent: Color(0xFF00AE7A), downColorProminent: Color(0xFFC40025), ); ``` -------------------------------- ### Controller for Advanced Interactive Layer Control Source: https://github.com/deriv-com/flutter-chart/blob/master/doc/interactive_layer_usage.md Use `InteractiveLayerController` to manage the interactive layer, enabling programmatic control like canceling tool additions and listening to state changes. ```dart // Create a controller instance final InteractiveLayerController controller = InteractiveLayerController(); // Pass the controller to the behavior final InteractiveLayerBehaviour behaviour = InteractiveLayerMobileBehaviour( controller: controller ); Chart( useDrawingToolsV2: true, interactiveLayerBehaviour: behaviour, mainSeries: CandleSeries(candles), // Other parameters... ) ``` -------------------------------- ### Update an Indicator by Index Source: https://github.com/deriv-com/flutter-chart/blob/master/doc/deriv_chart_widget_usage.md Update an existing indicator in the repository and on the chart by providing its index and the new configuration object. ```Dart repo.updateAt(index, updatedConfig), ```