From c75233b86991e088050559692f5f0aefec99de6e Mon Sep 17 00:00:00 2001 From: Ismail Alam Khan Date: Tue, 23 Mar 2021 03:15:18 +0600 Subject: [PATCH 1/2] migrated the examples to null-safety --- ...resso_roast_vintage_2.png => espresso.png} | Bin .../lib/demos/altitude_indicator/scene.dart | 48 ++++----- .../demos/ball_line_collision/scene/ball.dart | 14 +-- .../ball_line_collision/scene/scene.dart | 14 ++- example/lib/demos/bookmark_button/scene.dart | 30 +++--- .../lib/demos/breakout/scene/game_scene.dart | 46 ++++----- example/lib/demos/breakout/scene/hud.dart | 50 ++++----- example/lib/demos/breakout/scene/objects.dart | 12 +-- example/lib/demos/card_rotation/scene.dart | 16 +-- .../lib/demos/chart_bezier/bezier_points.dart | 37 ++++--- .../chart_bezier/curved_graph_scene.dart | 32 +++--- .../lib/demos/chart_mountain/chart_data.dart | 6 +- .../chart_mountain/scene/chart_graph.dart | 24 ++--- .../chart_mountain/scene/chart_scene.dart | 10 +- .../chart_mountain/scene/chart_title.dart | 8 +- .../lib/demos/chart_mountain/scene/utils.dart | 2 +- .../demos/color_picker/picker_container.dart | 2 +- .../demos/color_picker/scene/hue_scene.dart | 46 ++++----- .../demos/color_picker/scene/value_scene.dart | 33 +++--- example/lib/demos/color_picker/utils.dart | 4 +- .../scene/bubble_preloader.dart | 19 ++-- .../demos/colorful_loader/scene/scene.dart | 8 +- example/lib/demos/dialer/dialer_scene.dart | 8 +- example/lib/demos/dna_3d/scene.dart | 12 +-- .../drawing_pad/draw_pad_scene.dart | 18 ++-- .../drawing_pad_bezier/drawing_pad/pad.dart | 34 +++--- .../drawing_pad_bezier/drawing_pad/point.dart | 6 +- .../dripping_iv/scene/dripping_scene.dart | 31 +++--- example/lib/demos/elastic_band/scene.dart | 16 +-- .../expander_fab_menu/expander_fab_menu.dart | 42 ++++---- .../lib/demos/fb_reactions/fb_reactions.dart | 28 ++--- example/lib/demos/fb_reactions/model.dart | 4 +- .../demos/fb_reactions/scene/menu_item.dart | 30 +++--- .../demos/fb_reactions/scene/menu_scene.dart | 36 +++---- example/lib/demos/feeling_switch/scene.dart | 8 +- example/lib/demos/flower_gradient/scene.dart | 4 +- .../lib/demos/gauge_meter/gauge_scene.dart | 22 ++-- example/lib/demos/globe_3d/scene.dart | 11 +- .../demos/glowing_circle/glowing_scene.dart | 8 +- example/lib/demos/heart_reaction/scene.dart | 11 +- example/lib/demos/isma_chart/data.dart | 4 +- .../demos/isma_chart/scene/chart_cell.dart | 9 +- .../demos/isma_chart/scene/chart_scene.dart | 22 ++-- .../demos/isma_chart/scene/chart_sprite.dart | 22 ++-- .../demos/isma_chart/scene/dot_button.dart | 11 +- example/lib/demos/jelly_thing/scene.dart | 39 ++++--- example/lib/demos/lined_button/scene.dart | 46 ++++----- example/lib/demos/lungs/scene.dart | 7 +- example/lib/demos/mouse_repulsion/scene.dart | 18 ++-- example/lib/demos/murat_coffee/scene.dart | 12 +-- .../demos/nico_loading_indicator/scene.dart | 16 +-- .../demos/nokia_snake/game_page_widget.dart | 2 +- example/lib/demos/nokia_snake/game_scene.dart | 22 ++-- .../nokia_snake/mobile_button_widget.dart | 8 +- .../lib/demos/nokia_snake/nokia_snake.dart | 4 +- example/lib/demos/page_indicator/dot.dart | 34 +++--- example/lib/demos/page_indicator/scene.dart | 24 ++--- .../lib/demos/path_chart_stress/scene.dart | 14 +-- example/lib/demos/pie_chart/scene.dart | 20 ++-- example/lib/demos/pizza_box/scene.dart | 15 ++- example/lib/demos/raster_draw/scene.dart | 20 ++-- .../demos/rating_star/scene/rating_scene.dart | 14 +-- example/lib/demos/rating_star/scene/star.dart | 40 ++++---- .../run_hero_canvas/scene/hero_scene.dart | 35 ++++--- .../simple_interactions_scene.dart | 16 +-- .../simple_interactions/ui/my_button.dart | 16 ++- .../demos/simple_radial_menu/circ_menu.dart | 18 ++-- .../simple_shape/simple_shapes_scene.dart | 2 +- .../lib/demos/simple_toast/simple_toast.dart | 8 +- example/lib/demos/simple_toast/toast.dart | 32 +++--- .../lib/demos/simple_tween/simple_tween.dart | 2 +- .../simple_tween/simple_tween_scene.dart | 34 +++--- .../sorting_button/scene/root_scene.dart | 11 +- .../scene/sorting_button_scene.dart | 86 ++++++++-------- .../spiral_loader/spiral_loader_scene.dart | 12 +-- .../demos/splash_intro/scene/logo_drawer.dart | 14 ++- .../splash_intro/scene/splash_scene.dart | 42 ++++---- .../demos/submit_button/scene/my_button.dart | 24 ++--- .../lib/demos/submit_button/scene/scene.dart | 2 +- example/lib/demos/svg_icons/test_icons.dart | 2 +- .../lib/demos/svg_icons/test_svg_scene.dart | 27 +++-- example/lib/demos/trigrid/scene/scene.dart | 46 ++++----- example/lib/demos/trigrid/scene/tri_grid.dart | 24 ++--- .../demos/universo_flutter_intro/scene.dart | 38 +++---- example/lib/demos/xmas/xmas.dart | 4 +- example/lib/demos/xmas/xmas_scene.dart | 20 ++-- example/lib/main.dart | 9 ++ example/lib/utils/base_scene.dart | 2 +- example/lib/utils/demo_scene_widget.dart | 12 +-- example/lib/utils/svg_utils.dart | 86 ++++++++-------- example/pubspec.yaml | 3 +- lib/src/render/graphics.dart | 12 +-- lib/src/tween/src/wraps/common_wraps.dart | 2 +- lib/src/utils/svg_utils.dart | 97 +++++++++--------- pubspec.lock | 22 ++++ pubspec.yaml | 4 +- 96 files changed, 998 insertions(+), 979 deletions(-) rename example/assets/murat_coffee/{espresso_roast_vintage_2.png => espresso.png} (100%) diff --git a/example/assets/murat_coffee/espresso_roast_vintage_2.png b/example/assets/murat_coffee/espresso.png similarity index 100% rename from example/assets/murat_coffee/espresso_roast_vintage_2.png rename to example/assets/murat_coffee/espresso.png diff --git a/example/lib/demos/altitude_indicator/scene.dart b/example/lib/demos/altitude_indicator/scene.dart index 8f8f0e4..e930567 100644 --- a/example/lib/demos/altitude_indicator/scene.dart +++ b/example/lib/demos/altitude_indicator/scene.dart @@ -16,17 +16,17 @@ class AltitudIndicatorScene extends GSprite { /// inner circle. GSprite rotatorCircle = GSprite(); - GSprite movable; + GSprite? movable; double innerCircSeparation = 50.0; double outlineThickness1 = 18.0; double outlineThickness2 = 10.0; - double meterSize; + late double meterSize; final redColor = const Color(0xffDA5537); double valueMeterGap = 34.0; - double innerCircleSize; + late double innerCircleSize; - double get minStageSize => Math.min(stage.stageWidth, stage.stageHeight); + double get minStageSize => Math.min(stage!.stageWidth, stage!.stageHeight); @override void addedToStage() { @@ -43,12 +43,14 @@ class AltitudIndicatorScene extends GSprite { .endFill(); addChild(mainMask); mainContainer.mask = mainMask; + /// center pivot in the current bounding box of scene. alignPivot(); - stage.onResized.add(() { + stage!.onResized.add(() { /// position the scene in the middle of screen. - setPosition(stage.stageWidth / 2, stage.stageHeight / 2); + setPosition(stage!.stageWidth / 2, stage!.stageHeight / 2); + /// scale % accordingly. scale = minStageSize / meterSize; }); @@ -85,10 +87,10 @@ class AltitudIndicatorScene extends GSprite { createOutsideLines(); /// create some movement for the airplane! - stage.onEnterFrame.add(onEnterFrame); + stage!.onEnterFrame.add(onEnterFrame); } - bool isPressed(LogicalKeyboardKey key) => stage.keyboard.isPressed(key); + bool isPressed(LogicalKeyboardKey key) => stage!.keyboard!.isPressed(key); int getDirY() { if (isPressed(LogicalKeyboardKey.arrowDown)) { @@ -113,9 +115,9 @@ class AltitudIndicatorScene extends GSprite { var dirX = getDirX(); if (dirY != 0) { - movable.y += 1.2 * dirY; + movable!.y += 1.2 * dirY; } else { - movable.y += (-movable.y) / 20; + movable!.y += (-movable!.y) / 20; } if (dirX != 0) { @@ -126,16 +128,16 @@ class AltitudIndicatorScene extends GSprite { } var maxRangeY = valueMeterGap * 2; - if (movable.y > maxRangeY) { - movable.y = maxRangeY; - } else if (movable.y < -maxRangeY) { - movable.y = -maxRangeY; + if (movable!.y > maxRangeY) { + movable!.y = maxRangeY; + } else if (movable!.y < -maxRangeY) { + movable!.y = -maxRangeY; } // rotatorCircle.rotation += .01; } - GSprite drawRotator() { + GSprite? drawRotator() { /// background first. movable = GSprite(); @@ -150,9 +152,9 @@ class AltitudIndicatorScene extends GSprite { ground.alignPivot(Alignment.topCenter); line.alignPivot(Alignment.center); - movable.addChild(sky); - movable.addChild(ground); - movable.addChild(line); + movable!.addChild(sky); + movable!.addChild(ground); + movable!.addChild(line); /// another option to draw background. // var rotatorBackground = GShape(); @@ -173,12 +175,12 @@ class AltitudIndicatorScene extends GSprite { // movable.addChild(rotatorBackground); var elements = buildRotatorElements(); - movable.addChild(elements); - rotatorCircle.addChild(movable); + movable!.addChild(elements); + rotatorCircle.addChild(movable!); /// the red arrow should always stay in the same position... /// re-parent the element to the rotator circle. - var arrow = elements.getChildByName('arrow'); + var arrow = elements.getChildByName('arrow')!; rotatorCircle.addChild(arrow); return movable; } @@ -329,7 +331,7 @@ class AltitudIndicatorScene extends GSprite { GShape _buildLine({ double thickness = 3.0, - double rotationDegrees, + required double rotationDegrees, }) { var line = GShape(); line.graphics.lineStyle(thickness, kColorWhite); @@ -337,7 +339,7 @@ class AltitudIndicatorScene extends GSprite { line.graphics.lineTo((innerCircleSize + innerCircSeparation) / 2, 0); line.pivotX = line.width; line.rotation = deg2rad(rotationDegrees); - linesContainer?.addChild(line); + linesContainer.addChild(line); return line; } diff --git a/example/lib/demos/ball_line_collision/scene/ball.dart b/example/lib/demos/ball_line_collision/scene/ball.dart index d111020..cb091c3 100644 --- a/example/lib/demos/ball_line_collision/scene/ball.dart +++ b/example/lib/demos/ball_line_collision/scene/ball.dart @@ -3,20 +3,20 @@ import 'package:graphx/graphx.dart'; class Ball extends GShape { double radius, vx, vy; - Color color; + Color? color; Ball({ - double x, - double y, - this.radius, - this.vx, - this.vy, + double? x, + double? y, + required this.radius, + required this.vx, + required this.vy, this.color, }) { this.x = x; this.y = y; graphics - .beginFill(color.withOpacity(.8)) + .beginFill(color!.withOpacity(.8)) .lineStyle(6, kColorBlack) .drawCircle(0, 0, radius) .endFill() diff --git a/example/lib/demos/ball_line_collision/scene/scene.dart b/example/lib/demos/ball_line_collision/scene/scene.dart index 619bcf4..a7e4f4c 100644 --- a/example/lib/demos/ball_line_collision/scene/scene.dart +++ b/example/lib/demos/ball_line_collision/scene/scene.dart @@ -4,17 +4,15 @@ /// /// web demo: https://roi-graphx-balls-collision.surge.sh/#/ - import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; import 'ball.dart'; class CollisionScene extends GSprite { + double get sw => stage!.stageWidth; - double get sw => stage.stageWidth; - - double get sh => stage.stageHeight; + double get sh => stage!.stageHeight; /// lazy with the types :P var lines = []; @@ -37,12 +35,12 @@ class CollisionScene extends GSprite { addChild(ball); balls.add(ball); }); - stage.onMouseDown.add(_onMouseDown); + stage!.onMouseDown.add(_onMouseDown); } void _onMouseDown(input) { - stage.onMouseUp.addOnce((input) => stage.onMouseMove.removeAll()); - stage.onMouseMove.add((input) => points.add([mouseX, mouseY, 0.0])); + stage!.onMouseUp.addOnce((input) => stage!.onMouseMove.removeAll()); + stage!.onMouseMove.add((input) => points.add([mouseX, mouseY, 0.0])); points = >[ [mouseX, mouseY, 0.0] ]; @@ -133,4 +131,4 @@ class CollisionScene extends GSprite { } } } -} \ No newline at end of file +} diff --git a/example/lib/demos/bookmark_button/scene.dart b/example/lib/demos/bookmark_button/scene.dart index 14e7945..a7998a3 100644 --- a/example/lib/demos/bookmark_button/scene.dart +++ b/example/lib/demos/bookmark_button/scene.dart @@ -7,15 +7,15 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; class BookmarkButton extends GSprite { - double get sw => stage.stageWidth; + double get sw => stage!.stageWidth; - double get sh => stage.stageHeight; - GShape bg; - GText label; + double get sh => stage!.stageHeight; + late GShape bg; + late GText label; bool isOn = false; - static List _gifFrames; - GMovieClip bookmarkIco; - GDropShadowFilter shadow; + static List? _gifFrames; + late GMovieClip bookmarkIco; + GDropShadowFilter? shadow; /// remove if not in debug? (hot reload). @override @@ -27,7 +27,7 @@ class BookmarkButton extends GSprite { @override void addedToStage() { - stage.color = Color(0xffEDEFFB); + stage!.color = Color(0xffEDEFFB); bg = addChild(GShape()) as GShape; shadow = GDropShadowFilter( 6, @@ -37,7 +37,7 @@ class BookmarkButton extends GSprite { Color(0xffA4AADB).withOpacity(.43), ); bg.$useSaveLayerBounds = false; - bg.filters = [shadow]; + bg.filters = [shadow!]; label = GText.build( text: 'Bookmark', color: Colors.black.withOpacity(.7), @@ -49,10 +49,10 @@ class BookmarkButton extends GSprite { label.setPosition(sw - label.textWidth - 32, (sh - label.textHeight) / 2); _loadTexture(); onMouseDown.add((e) { - shadow.tween(duration: .3, blurX: 2, blurY: 2, distance: 1); + shadow!.tween(duration: .3, blurX: 2, blurY: 2, distance: 1); bg.tween(duration: .3, scale: .95); - stage.onMouseUp.addOnce((e) { - shadow.tween(duration: .5, blurX: 6, blurY: 6, distance: 6); + stage!.onMouseUp.addOnce((e) { + shadow!.tween(duration: .5, blurX: 6, blurY: 6, distance: 6); bg.tween(duration: .5, scale: 1); }); }); @@ -69,14 +69,14 @@ class BookmarkButton extends GSprite { Future _loadTexture() async { if (_gifFrames == null) { - var atlas = await ResourceLoader.loadGif( + var atlas = await (ResourceLoader.loadGif( 'assets/bookmark_button/bookmark.gif', resolution: 2, - cacheId: 'bookmark'); + cacheId: 'bookmark') as Future); _gifFrames = atlas.textureFrames; } bookmarkIco = - addChild(GMovieClip(frames: _gifFrames, fps: 50)) as GMovieClip; + addChild(GMovieClip(frames: _gifFrames!, fps: 50)) as GMovieClip; bookmarkIco.repeatable = false; bookmarkIco.alignPivot(); bookmarkIco.setPosition(label.x / 2 + 2, sh / 2); diff --git a/example/lib/demos/breakout/scene/game_scene.dart b/example/lib/demos/breakout/scene/game_scene.dart index 35e632f..082fd98 100644 --- a/example/lib/demos/breakout/scene/game_scene.dart +++ b/example/lib/demos/breakout/scene/game_scene.dart @@ -9,7 +9,7 @@ class BreakoutAtari extends GSprite { static const double gameW = 160; static const double gameH = 192; - static BreakoutAtari instance; + static late BreakoutAtari instance; final bricks = []; @@ -26,22 +26,22 @@ class BreakoutAtari extends GSprite { double brickH = 12.0; final wallW = 4.0; - int cols, rows; - double totalBrickSep; + int cols = 0, rows = 0; + late double totalBrickSep; - Paddle paddle; - Ball ball; - GSprite bicksContainer; - HUD hud; + late Paddle paddle; + late Ball ball; + late GSprite bicksContainer; + late HUD hud; bool movingLeft = false; bool movingRight = false; bool _isGameOver = false; int brokenBricksCount = 0; - double get sw => stage.stageWidth; + double get sw => stage!.stageWidth; - double get sh => stage.stageHeight; + double get sh => stage!.stageHeight; BreakoutAtari() { instance = this; @@ -122,18 +122,18 @@ class BreakoutAtari extends GSprite { _updatePause(); } }); - stage.onMouseDown.add((event) { + stage!.onMouseDown.add((event) { isDragging = true; stagePressX = mouseX; paddlePressX = paddle.x; - stage.onMouseUp.addOnce((event) { + stage!.onMouseUp.addOnce((event) { isDragging = false; }); }); // stage.color = Colors.black.value; // stage.showBoundsRect = true; - stage.maskBounds = true; - stage.keyboard.onUp.add((input) { + stage!.maskBounds = true; + stage!.keyboard!.onUp.add((input) { if (input.isKey(LogicalKeyboardKey.escape)) { isPaused = !isPaused; mps.emit1(GameEvents.action, isPaused); @@ -146,7 +146,7 @@ class BreakoutAtari extends GSprite { } }); - stage.keyboard.onDown.add((input) { + stage!.keyboard!.onDown.add((input) { if (input.arrowLeft || input.isKey(LogicalKeyboardKey.keyA)) { movingLeft = true; } else if (input.arrowRight || input.isKey(LogicalKeyboardKey.keyD)) { @@ -195,8 +195,8 @@ class BreakoutAtari extends GSprite { paddle.y = gameH - paddle.h - 10; alignPivot(); - stage.onResized.add(() { - var graphBounds = bounds; + stage!.onResized.add(() { + var graphBounds = bounds!; var r1 = sw / sh; var r2 = graphBounds.width / graphBounds.height; if (r1 < r2) { @@ -217,7 +217,7 @@ class BreakoutAtari extends GSprite { if (isDragging) { paddle.x = paddlePressX + (mouseX - stagePressX); } else { - var thrust = stage.keyboard.isShiftPressed ? 2.0 : 1.0; + var thrust = stage!.keyboard!.isShiftPressed ? 2.0 : 1.0; if (movingLeft) { paddle.vx = -paddle.speed; } else if (movingRight) { @@ -261,7 +261,7 @@ class BreakoutAtari extends GSprite { bricks.forEach((b) { if (!collides(b, ball)) return; removeBricks.add(b); - hud.showPoints(b.points, b.getBounds(this)); + hud.showPoints(b.points, b.getBounds(this)!); b.removeFromParent(); /// check speed @@ -295,8 +295,8 @@ class BreakoutAtari extends GSprite { } bool collides(GDisplayObject obj1, GDisplayObject obj2) { - var bounds1 = obj1.getBounds(this); - var bounds2 = obj2.getBounds(this); + var bounds1 = obj1.getBounds(this)!; + var bounds2 = obj2.getBounds(this)!; return bounds1.intersects(bounds2); } @@ -322,11 +322,11 @@ class BreakoutAtari extends GSprite { void _updatePause() { hud.showPause(isPaused); - final ticker = stage.scene.core.ticker; + final ticker = stage!.scene.core.ticker; if (isPaused) { - ticker.callNextFrame(ticker.pause); + ticker!.callNextFrame(ticker.pause); } else { - ticker.resume(); + ticker!.resume(); } } } diff --git a/example/lib/demos/breakout/scene/hud.dart b/example/lib/demos/breakout/scene/hud.dart index 389bfcc..b9149a0 100644 --- a/example/lib/demos/breakout/scene/hud.dart +++ b/example/lib/demos/breakout/scene/hud.dart @@ -7,7 +7,7 @@ import 'game_scene.dart'; class HUD extends GSprite { // ignore: non_constant_identifier_names - GText _score_tf, _balls_tf, _gameState_tf, _speedUp_tf; + GText? _score_tf, _balls_tf, _gameState_tf, _speedUp_tf; final w = BreakoutAtari.gameW; final h = BreakoutAtari.gameH; @@ -20,15 +20,15 @@ class HUD extends GSprite { var titleScore = _getText('SCORE', 4); titleScore.setPosition(textMargin, textMargin); _score_tf = _getText('0', 6); - _score_tf.setPosition(textMargin, 10); + _score_tf!.setPosition(textMargin, 10); var titleBall = _getText('BALL', 4); titleBall.alignPivot(Alignment.topRight); titleBall.setPosition(w - textMargin, textMargin); _balls_tf = _getText('3/3', 6); - _balls_tf.alignPivot(Alignment.topRight); - _balls_tf.setPosition(titleBall.x, 10); + _balls_tf!.alignPivot(Alignment.topRight); + _balls_tf!.setPosition(titleBall.x, 10); _gameState_tf = GText( text: 'GAME OVER', @@ -40,13 +40,13 @@ class HUD extends GSprite { ), paragraphStyle: ParagraphStyle(textAlign: TextAlign.center), ); - _gameState_tf.y = (h - _gameState_tf.textHeight) / 2; - addChild(_gameState_tf); + _gameState_tf!.y = (h - _gameState_tf!.textHeight) / 2; + addChild(_gameState_tf!); _speedUp_tf = _getText('SPEED UP!', 10); - _speedUp_tf.alignPivot(); - _speedUp_tf.setPosition(w / 2, h / 2); - _speedUp_tf.alpha = 0; + _speedUp_tf!.alignPivot(); + _speedUp_tf!.setPosition(w / 2, h / 2); + _speedUp_tf!.alpha = 0; setGameOver(false); } @@ -102,13 +102,13 @@ class HUD extends GSprite { void speedUp() { final offset = 10.0; GTween.killTweensOf(_speedUp_tf); - _speedUp_tf.y = h / 2; - _speedUp_tf.alpha = 0; - _speedUp_tf.tween(duration: .15, alpha: 1); - _speedUp_tf.tween(duration: 1.2, delay: .15, y: h / 2 - offset, alpha: 0); + _speedUp_tf!.y = h / 2; + _speedUp_tf!.alpha = 0; + _speedUp_tf!.tween(duration: .15, alpha: 1); + _speedUp_tf!.tween(duration: 1.2, delay: .15, y: h / 2 - offset, alpha: 0); } - GText _getText(String label, double size, [Shadow shadow]) { + GText _getText(String label, double size, [Shadow? shadow]) { var tf = GText( text: label, textStyle: TextStyle( @@ -124,32 +124,32 @@ class HUD extends GSprite { void showPause(bool isPaused) { if (isPaused) { - _gameState_tf.text = 'PAUSED'; - _gameState_tf.visible = true; + _gameState_tf!.text = 'PAUSED'; + _gameState_tf!.visible = true; } else { - _gameState_tf.visible = false; + _gameState_tf!.visible = false; } } void showWin() { - _gameState_tf.text = 'YOU WIN!'; - _gameState_tf.visible = true; + _gameState_tf!.text = 'YOU WIN!'; + _gameState_tf!.visible = true; } void setBalls(int numBalls, int maxBalls) { - _balls_tf.text = '$numBalls/$maxBalls'; - _balls_tf.alignPivot(Alignment.topRight); + _balls_tf!.text = '$numBalls/$maxBalls'; + _balls_tf!.alignPivot(Alignment.topRight); } void setScore(int points) { - _score_tf.text = '$points'; + _score_tf!.text = '$points'; } void setGameOver(bool flag) { - _gameState_tf.visible = false; + _gameState_tf!.visible = false; if (flag) { - _gameState_tf.text = 'GAME OVER'; - _gameState_tf.visible = true; + _gameState_tf!.text = 'GAME OVER'; + _gameState_tf!.visible = true; } } } diff --git a/example/lib/demos/breakout/scene/objects.dart b/example/lib/demos/breakout/scene/objects.dart index 3e9d43d..6b607f2 100644 --- a/example/lib/demos/breakout/scene/objects.dart +++ b/example/lib/demos/breakout/scene/objects.dart @@ -2,10 +2,10 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; abstract class GameObj extends GShape { - double w, h; - Color color; + double w = 0, h = 0; + Color? color; - void init(double w, double h, Color color) { + void init(double w, double h, Color? color) { this.w = w; this.h = h; this.color = color; @@ -28,7 +28,7 @@ class Ball extends GameObj { @override void _draw() { - graphics.beginFill(color).drawCircle(0, 0, w / 2).endFill(); + graphics.beginFill(color!).drawCircle(0, 0, w / 2).endFill(); } } @@ -38,7 +38,7 @@ class Paddle extends GameObj { @override void _draw() { - graphics.beginFill(color).drawRect(0, 0, w, h).endFill(); + graphics.beginFill(color!).drawRect(0, 0, w, h).endFill(); } } @@ -47,6 +47,6 @@ class Brick extends GameObj { @override void _draw() { - graphics.beginFill(color).drawRect(0, 0, w, h).endFill(); + graphics.beginFill(color!).drawRect(0, 0, w, h).endFill(); } } diff --git a/example/lib/demos/card_rotation/scene.dart b/example/lib/demos/card_rotation/scene.dart index 9b9cfa1..814a7ea 100644 --- a/example/lib/demos/card_rotation/scene.dart +++ b/example/lib/demos/card_rotation/scene.dart @@ -11,7 +11,7 @@ import 'package:graphx/graphx.dart'; class CardRotation3dScene extends GSprite { @override void addedToStage() { - stage.color = Color(0xffF8F6F4); + stage!.color = Color(0xffF8F6F4); initUi(); } @@ -103,7 +103,7 @@ Just 89.- THB''', 0x9E7878, 12.0, FontWeight.normal, 20 / 12); cardItemParent.mouseChildren = false; cardItemParent.useCursor = true; - stage.onEnterFrame.add((event) { + stage!.onEnterFrame.add((event) { var dx = cardItemParent.mouseX; var dy = cardItemParent.mouseY; var angle = Math.atan2(dy, dx); @@ -126,7 +126,7 @@ Just 89.- THB''', 0x9E7878, 12.0, FontWeight.normal, 20 / 12); ease: GEase.easeOutExpo, ); - stage.onMouseUp.addOnce((event) { + stage!.onMouseUp.addOnce((event) { cardItemParent.tween( duration: 1.2, scale: 1, @@ -144,13 +144,13 @@ Just 89.- THB''', 0x9E7878, 12.0, FontWeight.normal, 20 / 12); }); cardItemParent.alignPivot(); - stage.onResized.add(() { - cardItemParent.x = stage.stageWidth / 2; - cardItemParent.y = stage.stageHeight / 2; + stage!.onResized.add(() { + cardItemParent.x = stage!.stageWidth / 2; + cardItemParent.y = stage!.stageHeight / 2; }); - cardItemParent.x = stage.stageWidth / 2; - cardItemParent.y = stage.stageHeight / 2; + cardItemParent.x = stage!.stageWidth / 2; + cardItemParent.y = stage!.stageHeight / 2; // cardItemParent.rotationX = .2; } diff --git a/example/lib/demos/chart_bezier/bezier_points.dart b/example/lib/demos/chart_bezier/bezier_points.dart index f39a772..8092542 100644 --- a/example/lib/demos/chart_bezier/bezier_points.dart +++ b/example/lib/demos/chart_bezier/bezier_points.dart @@ -1,8 +1,8 @@ import 'package:graphx/graphx.dart'; class _BezierControlPoint { - GPoint prev; - GPoint next; + GPoint? prev; + GPoint? next; _BezierControlPoint([this.prev, this.next]) { prev ??= GPoint(); @@ -16,14 +16,13 @@ void bezierCurveThrough( Graphics g, List points, [ double tension = .25, - List output, + List? output, ]) { - tension ??= .25; var len = points.length; if (len == 2) { output?.addAll([points[0], points[1]]); - g?.moveTo(points[0].x, points[0].y); - g?.lineTo(points[1].x, points[1].y); + g.moveTo(points[0].x, points[0].y); + g.lineTo(points[1].x, points[1].y); return; } @@ -50,41 +49,41 @@ void bezierCurveThrough( var cnx = pi.x + dx * dn * tension; var cny = pi.y + dy * dn * tension; - cpoints[i].prev.setTo(cpx, cpy); - cpoints[i].next.setTo(cnx, cny); + cpoints[i].prev!.setTo(cpx, cpy); + cpoints[i].next!.setTo(cnx, cny); } /// end points cpoints[0].next = GPoint( - (points[0].x + cpoints[1].prev.x) / 2, - (points[0].y + cpoints[1].prev.y) / 2, + (points[0].x + cpoints[1].prev!.x) / 2, + (points[0].y + cpoints[1].prev!.y) / 2, ); cpoints[len - 1].prev = GPoint( - (points[len - 1].x + cpoints[len - 2].next.x) / 2, - (points[len - 1].y + cpoints[len - 2].next.y) / 2, + (points[len - 1].x + cpoints[len - 2].next!.x) / 2, + (points[len - 1].y + cpoints[len - 2].next!.y) / 2, ); /// draw? - g?.moveTo(points[0].x, points[0].y); + g.moveTo(points[0].x, points[0].y); output?.add(points[0]); for (var i = 1; i < len; ++i) { var p = points[i]; var cp = cpoints[i]; var cpp = cpoints[i - 1]; - g?.cubicCurveTo(cpp.next.x, cpp.next.y, cp.prev.x, cp.prev.y, p.x, p.y); + g.cubicCurveTo(cpp.next!.x, cpp.next!.y, cp.prev!.x, cp.prev!.y, p.x, p.y); output?.addAll([cpp.next, cp.prev, p]); } cpoints.clear(); } -void bezierCurveThroughDraw(Graphics g, List points) { - g.moveTo(points[0].x, points[0].y); +void bezierCurveThroughDraw(Graphics g, List points) { + g.moveTo(points[0]!.x, points[0]!.y); final len = points.length; for (var i = 1; i < len; i += 3) { - final p0 = points[i]; - final p1 = points[i + 1]; - final p2 = points[i + 2]; + final p0 = points[i]!; + final p1 = points[i + 1]!; + final p2 = points[i + 2]!; g.cubicCurveTo(p0.x, p0.y, p1.x, p1.y, p2.x, p2.y); } } diff --git a/example/lib/demos/chart_bezier/curved_graph_scene.dart b/example/lib/demos/chart_bezier/curved_graph_scene.dart index 52cf9c5..6164415 100644 --- a/example/lib/demos/chart_bezier/curved_graph_scene.dart +++ b/example/lib/demos/chart_bezier/curved_graph_scene.dart @@ -5,17 +5,17 @@ import 'bezier_points.dart'; class CurvedGraphScene extends GSprite { List graphPositions = [.2, .4, .9, .3, .6, .7, .9, .3]; - List bezierPoints; + List? bezierPoints; - double get graphW => stage.stageWidth; - double get graphH => stage.stageHeight; + double get graphW => stage!.stageWidth; + double get graphH => stage!.stageHeight; - GSprite graph, dots; - GShape lines, filled; - List coords; + late GSprite graph, dots; + late GShape lines, filled; + late List coords; - GTweenableList myTweenList; - List lastPercents; + late GTweenableList myTweenList; + late List lastPercents; GShape drawCircle(double px, double py) { var sh = GShape(); @@ -29,7 +29,7 @@ class CurvedGraphScene extends GSprite { void addedToStage() { bezierPoints = []; // stage.color = Colors.black; - stage.maskBounds=true; + stage!.maskBounds = true; graph = GSprite(); dots = GSprite(); @@ -54,7 +54,7 @@ class CurvedGraphScene extends GSprite { lastPercents = List.from(graphPositions); myTweenList = lastPercents.twn; randomNumbers(); - stage.onMouseClick.add((e) => randomNumbers()); + stage!.onMouseClick.add((e) => randomNumbers()); } void randomNumbers() { @@ -84,16 +84,16 @@ class CurvedGraphScene extends GSprite { newValues, duration: 2, onUpdate: () { - final values = myTweenList.value as List; + final values = myTweenList.value as List; renderPositions(values); }, ease: GEase.fastLinearToSlowEaseIn, ); } - void renderPositions(List percents) { + void renderPositions(List percents) { for (var i = 0; i < percents.length; ++i) { - coords[i].y = percents[i] * graphH; + coords[i].y = percents[i]! * graphH; dots.getChildAt(i).y = coords[i].y; } lines.graphics.clear(); @@ -106,7 +106,7 @@ class CurvedGraphScene extends GSprite { ], ratios: [.1, 1], ); - bezierPoints.clear(); + bezierPoints!.clear(); bezierCurveThrough(lines.graphics, coords, .25, bezierPoints); filled.graphics.clear(); @@ -120,11 +120,11 @@ class CurvedGraphScene extends GSprite { begin: Alignment.topCenter, end: Alignment.bottomCenter, ); - bezierCurveThroughDraw(filled.graphics, bezierPoints); + bezierCurveThroughDraw(filled.graphics, bezierPoints!); filled.graphics .lineTo(graphW, graphH) .lineTo(0, graphH) - .lineTo(bezierPoints[0].x, bezierPoints[0].y) + .lineTo(bezierPoints![0]!.x, bezierPoints![0]!.y) .endFill(); } } diff --git a/example/lib/demos/chart_mountain/chart_data.dart b/example/lib/demos/chart_mountain/chart_data.dart index 58eeacc..78e1458 100644 --- a/example/lib/demos/chart_mountain/chart_data.dart +++ b/example/lib/demos/chart_mountain/chart_data.dart @@ -11,8 +11,8 @@ const sampleGraphData = [ ]; class GraphModel { - final List data; - final Color color; - final String name; + final List? data; + final Color? color; + final String? name; const GraphModel({this.data, this.color, this.name}); } diff --git a/example/lib/demos/chart_mountain/scene/chart_graph.dart b/example/lib/demos/chart_mountain/scene/chart_graph.dart index c8ce3a0..8870636 100644 --- a/example/lib/demos/chart_mountain/scene/chart_graph.dart +++ b/example/lib/demos/chart_mountain/scene/chart_graph.dart @@ -4,9 +4,9 @@ import '../chart_data.dart'; import 'utils.dart'; class MyGraph extends GSprite { - GShape graph; - GSprite chartContainer, titlesContainer; - GShape background; + GShape? graph; + GSprite? chartContainer, titlesContainer; + late GShape background; double minValueY = 0, maxValueY = 160, stepY = 20; List xRange = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul']; @@ -14,12 +14,12 @@ class MyGraph extends GSprite { double graphW = 295; double graphH = 209; - double lineSepY, lineSepX; - int numLinesY, numLinesX; + double lineSepY = 0.0, lineSepX = 0.0; + int numLinesY = 0, numLinesX = 0; double minAlpha = .7; double maxAlpha = 1.0; - final List data; + final List? data; MyGraph({this.data}); @override @@ -28,7 +28,7 @@ class MyGraph extends GSprite { addChild(background); chartContainer = GSprite(); - addChild(chartContainer); + addChild(chartContainer!); numLinesY = ((minValueY + (maxValueY - minValueY)) ~/ stepY) + 1; numLinesX = xRange.length; @@ -70,18 +70,18 @@ class MyGraph extends GSprite { }); }); - chartContainer.addChild(graph); + chartContainer?.addChild(graph); drawChart(data, graph, 1); return graph; } - void drawChart(GraphModel data, GShape graph, [double percent = 1]) { + void drawChart(GraphModel data, GShape graph, [double? percent = 1]) { var g = graph.graphics; g.clear(); - g.beginFill(data.color); - var list = data.data; + g.beginFill(data.color!); + var list = data.data!; for (var i = 0; i < list.length; ++i) { - final valuePercent = list[i] / maxValueY * percent; + final valuePercent = list[i] / maxValueY * percent!; final relY = graphH - valuePercent * graphH; var px = i * lineSepX; if (i == 0) { diff --git a/example/lib/demos/chart_mountain/scene/chart_scene.dart b/example/lib/demos/chart_mountain/scene/chart_scene.dart index 671bae7..7269a44 100644 --- a/example/lib/demos/chart_mountain/scene/chart_scene.dart +++ b/example/lib/demos/chart_mountain/scene/chart_scene.dart @@ -6,16 +6,16 @@ import 'chart_graph.dart'; import 'chart_title.dart'; class SampleMountainChart extends GSprite { - MyGraph graph; - GraphTitle titles; + late MyGraph graph; + late GraphTitle titles; - double get sw => stage.stageWidth; + double get sw => stage!.stageWidth; - double get sh => stage.stageHeight; + double get sh => stage!.stageHeight; @override void addedToStage() { - stage.showBoundsRect = true; + stage!.showBoundsRect = true; graph = MyGraph(data: sampleGraphData); graph.x = 40; graph.y = 20; diff --git a/example/lib/demos/chart_mountain/scene/chart_title.dart b/example/lib/demos/chart_mountain/scene/chart_title.dart index e573557..920fc94 100644 --- a/example/lib/demos/chart_mountain/scene/chart_title.dart +++ b/example/lib/demos/chart_mountain/scene/chart_title.dart @@ -4,19 +4,19 @@ import '../chart_data.dart'; import 'utils.dart'; class GraphTitle extends GSprite { - final List data; + final List? data; GraphTitle({this.data}); @override void addedToStage() { - for (var i = 0; i < data.length; ++i) { - final vo = data[i]; + for (var i = 0; i < data!.length; ++i) { + final vo = data![i]; var item = GSprite(); addChild(item); var quad = GShape(); item.addChild(quad); - quad.graphics.beginFill(vo.color).drawRect(0, 0, 7, 7).endFill(); + quad.graphics.beginFill(vo.color!).drawRect(0, 0, 7, 7).endFill(); quad.y = 3; var title = createLabel(vo.name); item.addChild(title); diff --git a/example/lib/demos/chart_mountain/scene/utils.dart b/example/lib/demos/chart_mountain/scene/utils.dart index be8f3e0..d6fc7a9 100644 --- a/example/lib/demos/chart_mountain/scene/utils.dart +++ b/example/lib/demos/chart_mountain/scene/utils.dart @@ -1,4 +1,4 @@ import 'package:graphx/graphx.dart'; -GText createLabel(String text) => +GText createLabel(String? text) => GText.build(text: text, fontSize: 10, color: kColorBlack); diff --git a/example/lib/demos/color_picker/picker_container.dart b/example/lib/demos/color_picker/picker_container.dart index af3b718..2cc1b90 100644 --- a/example/lib/demos/color_picker/picker_container.dart +++ b/example/lib/demos/color_picker/picker_container.dart @@ -27,7 +27,7 @@ class PickerContainer extends StatelessWidget { child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - ValueListenableBuilder( + ValueListenableBuilder( valueListenable: pickerNotifier, builder: (ctx, value, _) => Container( width: 40, diff --git a/example/lib/demos/color_picker/scene/hue_scene.dart b/example/lib/demos/color_picker/scene/hue_scene.dart index 2ffecc8..36a0a2b 100644 --- a/example/lib/demos/color_picker/scene/hue_scene.dart +++ b/example/lib/demos/color_picker/scene/hue_scene.dart @@ -4,13 +4,13 @@ import 'package:graphx/graphx.dart'; import '../utils.dart'; class HueScene extends GSprite { - GShape colorSelector; - GShape arrowSelector; - GShape lineSelector; - Color _selectedColor; + late GShape colorSelector; + late GShape arrowSelector; + GShape? lineSelector; + Color? _selectedColor; - double sw, sh; - ByteData colorsBytes; + double sw = 0.0, sh = 0.0; + ByteData? colorsBytes; HueScene() { // config(usePointer: true, autoUpdateAndRender: true); @@ -22,8 +22,8 @@ class HueScene extends GSprite { var hvsList = List.generate(numHues, (index) { return HSVColor.fromAHSV(1, index / numHues * 360, 1, 1).toColor(); }); - sw = stage.stageWidth; - sh = stage.stageHeight; + sw = stage!.stageWidth; + sh = stage!.stageHeight; colorSelector = GShape(); colorSelector.graphics @@ -40,9 +40,9 @@ class HueScene extends GSprite { arrowSelector = GShape(); lineSelector = GShape(); - lineSelector.graphics.beginFill(kColorWhite).drawRect(0, 0, sw, 10); - lineSelector.alignPivot(Alignment.center); - lineSelector.x = sw / 2; + lineSelector!.graphics.beginFill(kColorWhite).drawRect(0, 0, sw, 10); + lineSelector!.alignPivot(Alignment.center); + lineSelector!.x = sw / 2; /// create the arrow GShape first arrowSelector.graphics.beginFill(kColorBlack).drawPolygonFaces( @@ -67,24 +67,24 @@ class HueScene extends GSprite { addChild(colorSelector); addChild(arrowSelector); - addChild(lineSelector); - lineSelector.alpha = 0; + addChild(lineSelector!); + lineSelector!.alpha = 0; mouseChildren = false; - lineSelector.scaleX = 0; - stage.onMouseDown.add((input) { + lineSelector!.scaleX = 0; + stage!.onMouseDown.add((input) { // lineSelector.y = sh / 2; GTween.killTweensOf(lineSelector); - lineSelector.height = 8; - lineSelector.tween( + lineSelector!.height = 8; + lineSelector!.tween( duration: .8, height: 2, scaleX: 1, alpha: 1, ease: GEase.easeOutExpo, ); - stage.onMouseUp.addOnce((input) { - lineSelector.tween( + stage!.onMouseUp.addOnce((input) { + lineSelector!.tween( duration: .8, scaleX: 0, height: 0, @@ -92,7 +92,7 @@ class HueScene extends GSprite { }); _updatePosition(); }); - stage.onMouseMove.add(_onMouseMove); + stage!.onMouseMove.add(_onMouseMove); /// get the image bytes from capturing the GShape snapshot. /// so we can get the colors from the bytes List. @@ -109,13 +109,13 @@ class HueScene extends GSprite { } void _updatePosition() { - lineSelector.y = arrowSelector.y = mouseY.clamp(0.0, sh - 1); + lineSelector!.y = arrowSelector.y = mouseY.clamp(0.0, sh - 1); updateColor(); } void updateColor() { _selectedColor = getPixelColor( - colorsBytes, + colorsBytes!, sw.toInt(), sh.toInt(), 0, @@ -123,6 +123,6 @@ class HueScene extends GSprite { ); /// emit the event to update the UI. - pickerMPS.emit1(ColorPickerEmitter.changeHue, _selectedColor); + pickerMPS.emit1(ColorPickerEmitter.changeHue, _selectedColor); } } diff --git a/example/lib/demos/color_picker/scene/value_scene.dart b/example/lib/demos/color_picker/scene/value_scene.dart index 10e2394..35ad9b4 100644 --- a/example/lib/demos/color_picker/scene/value_scene.dart +++ b/example/lib/demos/color_picker/scene/value_scene.dart @@ -4,21 +4,21 @@ import 'package:graphx/graphx.dart'; import '../utils.dart'; class ValueScene extends GSprite { - GShape bgColor; - GShape bgBrightness; - GShape bgValue; - GSprite colorsContainer; - ByteData colorsBytes; - GShape selector; - Color _selectedColor; - double sw, sh; + late GShape bgColor; + late GShape bgBrightness; + late GShape bgValue; + late GSprite colorsContainer; + ByteData? colorsBytes; + late GShape selector; + Color? _selectedColor; + double sw = 0.0, sh = 0.0; ValueScene(); @override void addedToStage() { - sw = stage.stageWidth; - sh = stage.stageHeight; + sw = stage!.stageWidth; + sh = stage!.stageHeight; bgColor = GShape(); bgColor.graphics @@ -52,16 +52,16 @@ class ValueScene extends GSprite { addChild(selector); mouseChildren = false; - stage.onMouseDown.add((e) { + stage!.onMouseDown.add((e) { _updateColor(); selector.tween(duration: .4, scale: 1.5); GMouse.hide(); - stage.onMouseUp.addOnce((e) { + stage!.onMouseUp.addOnce((e) { GMouse.show(); selector.tween(duration: .3, scale: 1); }); }); - stage.onMouseMove.add(_handleMouseMove); + stage!.onMouseMove.add(_handleMouseMove); pickerMPS.on(ColorPickerEmitter.changeHue, handleChangeHue); } @@ -77,7 +77,8 @@ class ValueScene extends GSprite { updateColor(); } - void drawGradient(Graphics graphics, {Color color, bool isHorizontal}) { + void drawGradient(Graphics graphics, + {required Color color, required bool isHorizontal}) { var from = isHorizontal ? Alignment.centerLeft : Alignment.bottomCenter; var to = isHorizontal ? Alignment.centerRight : Alignment.topCenter; graphics @@ -109,7 +110,7 @@ class ValueScene extends GSprite { void updateColor() { if (colorsBytes == null) return; _selectedColor = getPixelColor( - colorsBytes, + colorsBytes!, sw.toInt(), sh.toInt(), selector.x.toInt(), @@ -117,7 +118,7 @@ class ValueScene extends GSprite { ); /// emit the event to update the UI. - pickerNotifier.value = _selectedColor; + pickerNotifier.value = _selectedColor!; // pickerMPS.emit1(ColorPickerEmitter.changeValue, _selectedColor); } } diff --git a/example/lib/demos/color_picker/utils.dart b/example/lib/demos/color_picker/utils.dart index 13e9bad..25b8814 100644 --- a/example/lib/demos/color_picker/utils.dart +++ b/example/lib/demos/color_picker/utils.dart @@ -31,9 +31,9 @@ Color getPixelColor( return Color.fromARGB(a, r, g, b); } -Future getImageBytes(GDisplayObject object) async { +Future getImageBytes(GDisplayObject object) async { var texture = await object.createImageTexture(true, 1); - var data = texture.root.toByteData(format: ImageByteFormat.rawRgba); + var data = texture.root!.toByteData(format: ImageByteFormat.rawRgba); // texture?.dispose(); // texture = null; return data; diff --git a/example/lib/demos/colorful_loader/scene/bubble_preloader.dart b/example/lib/demos/colorful_loader/scene/bubble_preloader.dart index 73edcbc..172db2f 100644 --- a/example/lib/demos/colorful_loader/scene/bubble_preloader.dart +++ b/example/lib/demos/colorful_loader/scene/bubble_preloader.dart @@ -2,7 +2,6 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; class BubblePreloader extends GSprite { - static const gradientColors = [ Color(0xFF9874D3), Color(0xFF6E7CCC), @@ -13,9 +12,9 @@ class BubblePreloader extends GSprite { ]; double w, h; - GShape bg, percentMask, bgGradient; - GSprite percentContainer, bubblesContainer; - double borderRadius, percent = 0.25, gradientShift = 0.0; + GShape? bg, percentMask, bgGradient; + late GSprite percentContainer, bubblesContainer; + double borderRadius = 0.0, percent = 0.25, gradientShift = 0.0; Color bgColor = const Color(0xffDEE0E3); int numBubbles = 50; @@ -37,11 +36,11 @@ class BubblePreloader extends GSprite { bgGradient = GShape(); percentMask = GShape(); - percentContainer.addChild(bgGradient); + percentContainer.addChild(bgGradient!); percentContainer.addChild(bubblesContainer); - addChild(bg); + addChild(bg!); addChild(percentContainer); - addChild(percentMask); + addChild(percentMask!); percentContainer.mask = percentMask; _drawBack(); @@ -96,7 +95,7 @@ class BubblePreloader extends GSprite { } void _drawMask() { - percentMask.graphics + percentMask!.graphics .clear() .beginFill(bgColor) .drawRoundRect(0, 0, w * percent, h, borderRadius) @@ -114,7 +113,7 @@ class BubblePreloader extends GSprite { } void _drawBack() { - bg.graphics + bg!.graphics .beginFill(bgColor) .drawRoundRect(0, 0, w, h, borderRadius) .endFill(); @@ -125,7 +124,7 @@ class BubblePreloader extends GSprite { gradientShift %= 3; var a1 = -1.0 - gradientShift; var a2 = 4.0 - gradientShift; - bgGradient.graphics + bgGradient!.graphics .clear() .beginGradientFill( GradientType.linear, diff --git a/example/lib/demos/colorful_loader/scene/scene.dart b/example/lib/demos/colorful_loader/scene/scene.dart index f6fdb63..27b5a4e 100644 --- a/example/lib/demos/colorful_loader/scene/scene.dart +++ b/example/lib/demos/colorful_loader/scene/scene.dart @@ -11,7 +11,7 @@ import 'bubble_preloader.dart'; /// just a wrapper scene class. class ColorLoaderScene extends GSprite { - BubblePreloader loader; + late BubblePreloader loader; @override void addedToStage() { @@ -21,11 +21,11 @@ class ColorLoaderScene extends GSprite { loader = BubblePreloader(w: 385, h: 14); addChild(loader); - stage.onResized.add(_handleStageResize); + stage!.onResized.add(_handleStageResize); } void _handleStageResize() { - loader.x = (stage.stageWidth - loader.w) / 2; - loader.y = (stage.stageHeight - loader.h) / 2; + loader.x = (stage!.stageWidth - loader.w) / 2; + loader.y = (stage!.stageHeight - loader.h) / 2; } } diff --git a/example/lib/demos/dialer/dialer_scene.dart b/example/lib/demos/dialer/dialer_scene.dart index 37e83e1..7b185ca 100644 --- a/example/lib/demos/dialer/dialer_scene.dart +++ b/example/lib/demos/dialer/dialer_scene.dart @@ -12,7 +12,7 @@ import 'package:graphx/graphx.dart'; const pinkColor = Color(0xffDD3D5C); class DialerScene extends GSprite { - Dialer dialer; + late Dialer dialer; @override void addedToStage() { @@ -26,11 +26,11 @@ class Dialer extends GSprite { double radius = 700 / 2; bool isPressed = false; GPoint pressed = GPoint(); - GShape bg; + late GShape bg; double prevRot = 0.0; double pressRot = 0.0; - Dialer([GSprite doc]) { + Dialer([GSprite? doc]) { _draw(); doc?.addChild(this); @@ -42,7 +42,7 @@ class Dialer extends GSprite { pressed.setTo(mouseX, mouseY); prevRot = bg.rotation; pressRot = Math.atan2(mouseY, mouseX); //bg.rotation; - stage.onMouseUp.add( + stage!.onMouseUp.add( (event) => isPressed = false, ); }); diff --git a/example/lib/demos/dna_3d/scene.dart b/example/lib/demos/dna_3d/scene.dart index 4bd0423..48bd668 100644 --- a/example/lib/demos/dna_3d/scene.dart +++ b/example/lib/demos/dna_3d/scene.dart @@ -2,14 +2,14 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; class DnaScene extends GSprite { - double spiralRadius, centerX, centerY, centerZ; + double spiralRadius = 0.0, centerX = 0.0, centerY = 0.0, centerZ = 0.0; double fl = 150; - List dots; + late List dots; @override void addedToStage() async { - stage.color = Colors.white; + stage!.color = Colors.white; dots = List.generate(80, (index) { var dot = Dot(); addChild(dot); @@ -22,8 +22,8 @@ class DnaScene extends GSprite { @override void update(double delta) { super.update(delta); - centerX = stage.stageWidth / 2; - centerY = stage.stageHeight / 2; + centerX = stage!.stageWidth / 2; + centerY = stage!.stageHeight / 2; centerZ = 100.0; spiralRadius = (mouseX - centerX) / 4; @@ -47,7 +47,7 @@ class DnaScene extends GSprite { /// we just make a class to store the basic properties /// for the calculations. class Dot extends GShape { - double py, angle, speed = 5; + double py = 0.0, angle = 0.0, speed = 5; Dot() { graphics.beginFill(kColorBlack).drawCircle(0, 0, 10).endFill(); diff --git a/example/lib/demos/drawing_pad_bezier/drawing_pad/draw_pad_scene.dart b/example/lib/demos/drawing_pad_bezier/drawing_pad/draw_pad_scene.dart index 893f6ee..08aba9f 100644 --- a/example/lib/demos/drawing_pad_bezier/drawing_pad/draw_pad_scene.dart +++ b/example/lib/demos/drawing_pad_bezier/drawing_pad/draw_pad_scene.dart @@ -6,9 +6,9 @@ import 'pad.dart'; class DrawPadScene extends GSprite { int colorCount = 0; - double get sw => stage.stageWidth; + double get sw => stage!.stageWidth; - double get sh => stage.stageHeight; + double get sh => stage!.stageHeight; double targetRot = 0; double opacity = 1.0; @@ -20,9 +20,9 @@ class DrawPadScene extends GSprite { @override void addedToStage() async { - stage.onHotReload.addOnce(() { - stage.onMouseScroll.removeAll(); - stage.onMouseMove.removeAll(); + stage!.onHotReload.addOnce(() { + stage!.onMouseScroll.removeAll(); + stage!.onMouseMove.removeAll(); mps.offAll('color'); mps.offAll('clear'); }); @@ -35,11 +35,11 @@ class DrawPadScene extends GSprite { pad.onBegin = GMouse.hide; pad.onEnd = GMouse.show; - stage.onMouseScroll.add((event) { + stage!.onMouseScroll.add((event) { var dir = event.scrollDelta.y; if (dir == 0) return; dir = dir < 0 ? 1 : -1; - if (stage.keyboard.isShiftPressed) { + if (stage!.keyboard!.isShiftPressed) { pad.minW += (dir * .1); pad.minW = pad.minW.clamp(minRad, maxRad); } else { @@ -47,13 +47,13 @@ class DrawPadScene extends GSprite { pad.maxW = pad.maxW.clamp(minRad, maxRad); } }); - stage.onResized.add(() => pad.resize(sw, sh)); + stage!.onResized.add(() => pad.resize(sw, sh)); pad.minW = .2; pad.maxW = 12.2; mps.on('alpha', (double alpha) { opacity = alpha; - pad.canvas.alpha = alpha; + pad.canvas!.alpha = alpha; }); mps.on('color', (Color color) { pad.penColor = color; diff --git a/example/lib/demos/drawing_pad_bezier/drawing_pad/pad.dart b/example/lib/demos/drawing_pad_bezier/drawing_pad/pad.dart index 94be25c..87ec134 100644 --- a/example/lib/demos/drawing_pad_bezier/drawing_pad/pad.dart +++ b/example/lib/demos/drawing_pad_bezier/drawing_pad/pad.dart @@ -15,24 +15,24 @@ class Pad extends GSprite { Color penColor = Color(0xff000000); Color backgroundColor = Colors.black; - Function onBegin, onEnd, onUpdate; + Function? onBegin, onEnd, onUpdate; final List _lastPoints = []; double _lastVelocity = 0; double _lastWidth = 0; - GShape _canvas; + GShape? _canvas; - GShape _bg; + late GShape _bg; - GShape get canvas => _canvas; - Graphics _g; + GShape? get canvas => _canvas; + late Graphics _g; double w, h; Pad({this.w = 300, this.h = 200}) { _canvas = GShape(); _bg = GShape(); addChild(_bg); - addChild(_canvas); - _g = _canvas.graphics; + addChild(_canvas!); + _g = _canvas!.graphics; clear(); on(); } @@ -51,11 +51,7 @@ class Pad extends GSprite { .beginFill(backgroundColor) .drawRect(0, 0, w, h) .endFill(); - _g - .clear() - .beginFill(baseTransparent) - .drawRect(0, 0, w, h) - .endFill(); + _g.clear().beginFill(baseTransparent).drawRect(0, 0, w, h).endFill(); _data.clear(); _reset(); _isEmpty = true; @@ -76,7 +72,7 @@ class Pad extends GSprite { void off() { onMouseDown.remove(_handleMouseDown); onMouseMove.remove(_handleMouseMove); - stage?.onMouseUp?.remove(_handleMouseUp); + stage?.onMouseUp.remove(_handleMouseUp); } void on() { @@ -85,7 +81,7 @@ class Pad extends GSprite { } _handleMouseDown(MouseInputData input) { - stage.onMouseUp.addOnce(_handleMouseUp); + stage!.onMouseUp.addOnce(_handleMouseUp); _isMouseDown = true; _strokeBegin(input); } @@ -125,15 +121,15 @@ class Pad extends GSprite { return; } - final mx = _canvas.mouseX; - final my = _canvas.mouseY; + final mx = _canvas!.mouseX; + final my = _canvas!.mouseY; final point = _createPoint(mx, my); final lastPointData = _data.last; var lastPoints = lastPointData.points; var lastPoint = lastPoints.isNotEmpty ? lastPoints.last : null; var hasLastPoint = lastPoint != null; var isLastPointTooClose = - hasLastPoint ? point.distanceTo(lastPoint) <= minDist : false; + hasLastPoint ? point.distanceTo(lastPoint!) <= minDist : false; final color = lastPointData.color; if (!hasLastPoint || !(hasLastPoint && isLastPointTooClose)) { @@ -150,7 +146,7 @@ class Pad extends GSprite { PadPoint _createPoint(double px, double py) => PadPoint(px, py, getTimer()); - BezierDraw _addPoint(PadPoint point) { + BezierDraw? _addPoint(PadPoint point) { _lastPoints.add(point); if (_lastPoints.length > 2) { if (_lastPoints.length == 3) { @@ -231,7 +227,7 @@ class Pad extends GSprite { class _StrokeData { Color color; - List points; + late List points; _StrokeData(this.color) { points = []; diff --git a/example/lib/demos/drawing_pad_bezier/drawing_pad/point.dart b/example/lib/demos/drawing_pad_bezier/drawing_pad/point.dart index 88e8b43..4bc48b9 100644 --- a/example/lib/demos/drawing_pad_bezier/drawing_pad/point.dart +++ b/example/lib/demos/drawing_pad_bezier/drawing_pad/point.dart @@ -4,8 +4,8 @@ import 'package:graphx/graphx.dart'; class PadPoint { double x, y; - int time; - PadPoint(this.x, this.y, [int time]) { + int? time; + PadPoint(this.x, this.y, [int? time]) { this.time = time ?? getTimer(); } @@ -15,7 +15,7 @@ class PadPoint { } double velocityForm(PadPoint start) => - time != start.time ? distanceTo(start) / (time - start.time) : 0.0; + time != start.time ? distanceTo(start) / (time! - start.time!) : 0.0; PadPoint operator -(PadPoint other) => PadPoint(x - other.x, y - other.y); PadPoint operator +(PadPoint other) => PadPoint(x + other.x, y + other.y); diff --git a/example/lib/demos/dripping_iv/scene/dripping_scene.dart b/example/lib/demos/dripping_iv/scene/dripping_scene.dart index a101a32..dffe144 100644 --- a/example/lib/demos/dripping_iv/scene/dripping_scene.dart +++ b/example/lib/demos/dripping_iv/scene/dripping_scene.dart @@ -1,17 +1,16 @@ -import '../../../utils/svg_utils.dart'; import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; import 'svgs.dart'; class DrippingScene extends GSprite { - GSvgShape drop; + late GSvgShape drop; double tubeW = 38, tubeH = 157, tubeOffset = 4.0; - GSprite tubeContainer; - GShape water, tubeMask; + late GSprite tubeContainer; + GShape? water, tubeMask; @override Future addedToStage() async { - stage.color = Colors.red; + stage!.color = Colors.red; var dropData = await SvgUtils.svgDataFromString(dropSvg); var tubeData = await SvgUtils.svgDataFromString(tubeSvgString); final waterColor = Colors.white; @@ -19,16 +18,16 @@ class DrippingScene extends GSprite { var tube = GSvgShape(tubeData); addChild(tube); tubeMask = GShape(); - tubeMask.setPosition(13, 29); - tubeMask.graphics + tubeMask!.setPosition(13, 29); + tubeMask!.graphics .beginFill(Colors.white.withOpacity(.2)) .drawRoundRect(tubeOffset, tubeOffset, tubeW - tubeOffset * 2, tubeH - tubeOffset * 2, tubeW / 2) .endFill(); - addChild(tubeMask); + addChild(tubeMask!); tubeContainer = GSprite(); - tubeContainer.setPosition(tubeMask.x, tubeMask.y); + tubeContainer.setPosition(tubeMask!.x, tubeMask!.y); tubeContainer.mask = tubeMask; addChild(tubeContainer); @@ -39,12 +38,12 @@ class DrippingScene extends GSprite { tubeContainer.addChild(drop); water = GShape(); - water.graphics + water!.graphics .beginFill(waterColor.withOpacity(.5)) .drawRect(0, 0, tubeW, 30); - water.alignPivot(Alignment.bottomLeft); - water.y = tubeH; - tubeContainer.addChild(water); + water!.alignPivot(Alignment.bottomLeft); + water!.y = tubeH; + tubeContainer.addChild(water!); addParticles(); // moveWater(); @@ -52,7 +51,7 @@ class DrippingScene extends GSprite { /// This shouldnt be needed... if u wrap in a Sized widget. alignPivot(); - setPosition(stage.stageWidth / 2, stage.stageHeight / 2); + setPosition(stage!.stageWidth / 2, stage!.stageHeight / 2); } void resetDripping() { @@ -63,10 +62,10 @@ class DrippingScene extends GSprite { } void moveWater() { - double targetH = water.height > 10 ? 5 : tubeH / 2; + double targetH = water!.height > 10 ? 5 : tubeH / 2; /// toggle water box height up and down... - water.tween( + water!.tween( duration: 6, height: targetH, ease: GEase.linearToEaseOut, diff --git a/example/lib/demos/elastic_band/scene.dart b/example/lib/demos/elastic_band/scene.dart index c7b2e0f..8e40506 100644 --- a/example/lib/demos/elastic_band/scene.dart +++ b/example/lib/demos/elastic_band/scene.dart @@ -13,14 +13,14 @@ class ElasticBandScene extends GSprite { @override void addedToStage() { - stage.onMouseDown.add(_handleMouseDown); + stage!.onMouseDown.add(_handleMouseDown); _handleUp(null); } void _handleMouseDown(e) { isPressed = true; - stage.onMouseMove.add(_handleMouseMove); - stage.onMouseUp.addOnce(_handleUp); + stage!.onMouseMove.add(_handleMouseMove); + stage!.onMouseUp.addOnce(_handleUp); } void _handleMouseMove(e) { @@ -28,11 +28,11 @@ class ElasticBandScene extends GSprite { } void _handleUp(e) { - stage.onMouseMove.remove(_handleMouseMove); + stage!.onMouseMove.remove(_handleMouseMove); isPressed = false; tweenPoint( - stage.stageWidth / 2, - stage.stageHeight / 2, + stage!.stageWidth / 2, + stage!.stageHeight / 2, 1, GEase.elasticOut, ); @@ -53,8 +53,8 @@ class ElasticBandScene extends GSprite { } void drawLine() { - var sw = stage.stageWidth; - var sh = stage.stageHeight; + var sw = stage!.stageWidth; + var sh = stage!.stageHeight; var cx = sw / 2; graphics diff --git a/example/lib/demos/expander_fab_menu/expander_fab_menu.dart b/example/lib/demos/expander_fab_menu/expander_fab_menu.dart index 4672c6a..fe5d8b3 100644 --- a/example/lib/demos/expander_fab_menu/expander_fab_menu.dart +++ b/example/lib/demos/expander_fab_menu/expander_fab_menu.dart @@ -44,9 +44,9 @@ class ExpanderFabMenu extends StatelessWidget { } class MyMenu extends StatefulWidget { - final Widget child; + final Widget? child; - const MyMenu({Key key, this.child}) : super(key: key); + const MyMenu({Key? key, this.child}) : super(key: key); @override _MyMenuState createState() => _MyMenuState(); @@ -55,7 +55,7 @@ class MyMenu extends StatefulWidget { class _MyMenuState extends State with TickerProviderStateMixin { bool isOpen = false; - AnimationController anim; + AnimationController? anim; final GlobalKey mySuperKey = GlobalKey(); final menuScene = MyCoolMenuScene(); @@ -69,14 +69,14 @@ class _MyMenuState extends State with TickerProviderStateMixin { // anim.addListener(() { // setState(() {}); // }); - WidgetsBinding.instance.addPostFrameCallback((timeStamp) { + WidgetsBinding.instance!.addPostFrameCallback((timeStamp) { getPosition(); }); } void getPosition() { - var ro = mySuperKey.currentContext.findRenderObject() as RenderBox; - var menuRO = context.findRenderObject() as RenderBox; + var ro = mySuperKey.currentContext!.findRenderObject() as RenderBox; + var menuRO = context.findRenderObject() as RenderBox?; var position = ro.localToGlobal(Offset.zero, ancestor: menuRO); menuScene.updatePosition(GRect.fromNative(position & ro.size)); } @@ -95,7 +95,7 @@ class _MyMenuState extends State with TickerProviderStateMixin { // color: Colors.red, child: Column( children: [ - Expanded(child: widget.child), + Expanded(child: widget.child!), Container( height: 60, decoration: BoxDecoration(color: Colors.white, boxShadow: [ @@ -165,7 +165,7 @@ class _MyMenuState extends State with TickerProviderStateMixin { } class MyCoolMenuScene extends GSprite { - MyButton button; + late MyButton button; bool isOpen = false; @@ -173,15 +173,15 @@ class MyCoolMenuScene extends GSprite { button = MyButton(); } - double buttonY; - GShape curtain; + double? buttonY; + late GShape curtain; void updatePosition(GRect position) { button.x = position.x + position.width / 2; button.y = buttonY = position.y + position.height / 2; } - GSprite menuContainer; + GSprite? menuContainer; @override void addedToStage() { @@ -190,7 +190,7 @@ class MyCoolMenuScene extends GSprite { addChild(curtain); menuContainer = GSprite(); - addChild(menuContainer); + addChild(menuContainer!); _buildMenu(); addChild(button); @@ -235,17 +235,17 @@ class MyCoolMenuScene extends GSprite { }); } - double get sw => stage.stageWidth; + double get sw => stage!.stageWidth; - double get sh => stage.stageHeight; - var twnCurtainY = 0.0; + double get sh => stage!.stageHeight; + double? twnCurtainY = 0.0; bool bounceCurtain = false; _bounceCurtain() { if (bounceCurtain) return; bounceCurtain = true; - final myTween = twnCurtainY.twn; + final myTween = twnCurtainY!.twn; myTween.tween( sh, duration: 1, @@ -267,7 +267,7 @@ class MyCoolMenuScene extends GSprite { // g.lineStyle(2, Colors.black); g.beginFill(Colors.red); g.moveTo(0, sh); - g.curveTo(button.x, sh, button.x, twnCurtainY); + g.curveTo(button.x, sh, button.x, twnCurtainY!); g.curveTo(button.x, sh, sw, sh); g.lineTo(sw, 0).lineTo(0, 0).closePath(); } @@ -289,8 +289,8 @@ class MyCoolMenuScene extends GSprite { itm.y = i * 34.0; items.add(itm); } - menuContainer.alignPivot(); - menuContainer.setPosition(sw / 2, sh / 2); + menuContainer!.alignPivot(); + menuContainer!.setPosition(sw / 2, sh / 2); } void showMenuNow() { @@ -309,8 +309,8 @@ class MyCoolMenuScene extends GSprite { } class MyButton extends GSprite { - GShape bg; - GIcon icon; + late GShape bg; + late GIcon icon; double radius = 20; @override diff --git a/example/lib/demos/fb_reactions/fb_reactions.dart b/example/lib/demos/fb_reactions/fb_reactions.dart index 5840af6..b240406 100644 --- a/example/lib/demos/fb_reactions/fb_reactions.dart +++ b/example/lib/demos/fb_reactions/fb_reactions.dart @@ -56,9 +56,9 @@ class FacebookReactionsMain extends StatelessWidget { } class InnerCardItem extends StatelessWidget { - final PostVo data; + final PostVo? data; - const InnerCardItem({Key key, this.data}) : super(key: key); + const InnerCardItem({Key? key, this.data}) : super(key: key); @override Widget build(BuildContext context) { @@ -82,14 +82,14 @@ class InnerCardItem extends StatelessWidget { radius: 24, /// dev channel // foregroundImage: NetworkImage(data.profileImageUrl), - child: Text(data.username[0].toUpperCase()), + child: Text(data!.username[0].toUpperCase()), ), const SizedBox(width: 8), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - data.username, + data!.username, style: const TextStyle( fontSize: 13, fontWeight: FontWeight.bold, @@ -97,7 +97,7 @@ class InnerCardItem extends StatelessWidget { ), const SizedBox(height: 4), Text( - data.time, + data!.time, style: const TextStyle( fontSize: 10, color: Colors.black38, @@ -111,7 +111,7 @@ class InnerCardItem extends StatelessWidget { const SizedBox(height: 8), Text( - data.title, + data!.title, style: const TextStyle( fontWeight: FontWeight.bold, fontSize: 15, @@ -133,7 +133,7 @@ class InnerCardItem extends StatelessWidget { ), clipBehavior: Clip.antiAlias, child: Image.network( - data.imageUrl, + data!.imageUrl, height: 240, fit: BoxFit.cover, ), @@ -143,12 +143,12 @@ class InnerCardItem extends StatelessWidget { Row( children: [ - _IconReaction.likes(count: data.numLikes), + _IconReaction.likes(count: data!.numLikes), const SizedBox(width: 12), - _IconReaction.comments(count: data.numComments), + _IconReaction.comments(count: data!.numComments), Spacer(), Text( - data.shares, + data!.shares, style: const TextStyle( fontSize: 10, color: Colors.black, @@ -167,12 +167,12 @@ class InnerCardItem extends StatelessWidget { } class _IconReaction extends StatelessWidget { - final IconData iconData; + final IconData? iconData; final Color color; - final int count; + final int? count; const _IconReaction({ - Key key, + Key? key, this.iconData, this.color = Colors.black, this.count, @@ -194,7 +194,7 @@ class _IconReaction extends StatelessWidget { children: [ Icon( iconData, - color: color ?? Colors.black, + color: color, size: 16, ), const SizedBox(width: 2), diff --git a/example/lib/demos/fb_reactions/model.dart b/example/lib/demos/fb_reactions/model.dart index 7a7c3c8..5ae47af 100644 --- a/example/lib/demos/fb_reactions/model.dart +++ b/example/lib/demos/fb_reactions/model.dart @@ -39,8 +39,8 @@ class PostVo { final String imageUrl; final String time; - int numLikes, numComments; - String shares; + int? numLikes, numComments; + late String shares; PostVo._( this.username, diff --git a/example/lib/demos/fb_reactions/scene/menu_item.dart b/example/lib/demos/fb_reactions/scene/menu_item.dart index aa7211b..0a9194d 100644 --- a/example/lib/demos/fb_reactions/scene/menu_item.dart +++ b/example/lib/demos/fb_reactions/scene/menu_item.dart @@ -3,11 +3,11 @@ import 'package:graphx/graphx.dart'; //// each face class MenuItem extends GSprite { - double size, targetTooltipY; - GSprite pill; - GShape bg, msk; - GText label; - GMovieClip emoji; + double? size, targetTooltipY; + late GSprite pill; + GShape? bg, msk; + late GText label; + late GMovieClip emoji; MenuItem([this.size = 60]) { _init(); @@ -18,16 +18,16 @@ class MenuItem extends GSprite { /// bg is the emoji face. bg = GShape(); - addChild(bg); - bg.graphics + addChild(bg!); + bg!.graphics .beginFill(Colors.black.withOpacity(.5)) - .drawCircle(0, 0, size / 2) + .drawCircle(0, 0, size! / 2) .endFill(); msk = GShape(); - addChild(msk); - msk.graphics.copyFrom(bg.graphics); - msk.mouseEnabled = false; + addChild(msk!); + msk!.graphics.copyFrom(bg!.graphics); + msk!.mouseEnabled = false; emoji = GMovieClip(frames: []); addChild(emoji); mouseChildren = false; @@ -50,7 +50,7 @@ class MenuItem extends GSprite { pill.mouseEnabled = false; pill.scale = .75; pill.addChild(label); - targetTooltipY = -size * .9; + targetTooltipY = -size! * .9; } void showTooltip(bool flag) { @@ -69,7 +69,7 @@ class MenuItem extends GSprite { pill.scale = .75; pill.addChild(label); pill.alignPivot(); - targetTooltipY = -size * .9; + targetTooltipY = -size! * .9; } void drawBackground() { @@ -87,9 +87,9 @@ class MenuItem extends GSprite { } void _setGifAtlas(String gifId) { - final myAtlas = ResourceLoader.getGif(gifId); + final myAtlas = ResourceLoader.getGif(gifId)!; emoji.setFrameTextures(myAtlas.textureFrames); - emoji.width = size + 2; + emoji.width = size! + 2; emoji.mask = bg; emoji.scaleY = emoji.scaleX; emoji.mouseEnabled = false; diff --git a/example/lib/demos/fb_reactions/scene/menu_scene.dart b/example/lib/demos/fb_reactions/scene/menu_scene.dart index 3f8e714..db880d1 100644 --- a/example/lib/demos/fb_reactions/scene/menu_scene.dart +++ b/example/lib/demos/fb_reactions/scene/menu_scene.dart @@ -36,34 +36,34 @@ class MenuScene extends GSprite { 'assets/fb_reactions/angry.gif', ), ]; - List _items; + late List _items; - double get sw => stage.stageWidth; + double get sw => stage!.stageWidth; - double get sh => stage.stageHeight; + double get sh => stage!.stageHeight; /// calculated based on bigSize and menuW - double itemSize; - double bigSizeScale; + double? itemSize; + double? bigSizeScale; double bigSize = 120.0; int numItems = emotions.length; - GShape bg; - GSprite menuContainer; + late GShape bg; + late GSprite menuContainer; double menuWidth = 400; double itemSep = 10; double bgPadding = 20; - MenuItem currentItem; + MenuItem? currentItem; @override Future addedToStage() async { final availableMenuW = (menuWidth - bgPadding * 2 - (numItems - 1) * itemSep); itemSize = (availableMenuW - bigSize) / (numItems - 1); - bigSizeScale = bigSize / itemSize; + bigSizeScale = bigSize / itemSize!; - final bgH = itemSize + bgPadding * 2; + final bgH = itemSize! + bgPadding * 2; menuContainer = GSprite(); addChild(menuContainer); bg = GShape(); @@ -98,7 +98,7 @@ class MenuScene extends GSprite { rotation: 0, ease: GEase.elasticOut); - stage.onMouseUp.addOnce((event) { + stage!.onMouseUp.addOnce((event) { menuContainer.tween( duration: .5, delay: .2, @@ -145,26 +145,26 @@ class MenuScene extends GSprite { var prevX = bgPadding; for (var i = 0; i < _items.length; ++i) { var itm = _items[i]; - var size2 = itm.size / 2; + var size2 = itm.size! / 2; itm.y = bgPadding + size2; size2 *= itm.scale; itm.x = prevX + size2; prevX += size2 * 2 + itemSep; - itm.onMouseOver.add((signal) => _selectItem(signal.target as MenuItem)); + itm.onMouseOver.add((signal) => _selectItem(signal.target as MenuItem?)); } } - void _selectItem(MenuItem item) { + void _selectItem(MenuItem? item) { if (item == currentItem) return; if (currentItem != null) { - currentItem.showTooltip(false); + currentItem!.showTooltip(false); GTween.killTweensOf(currentItem); - currentItem.tween(duration: .3, scale: 1); + currentItem!.tween(duration: .3, scale: 1); } currentItem = item; - currentItem.showTooltip(true); + currentItem!.showTooltip(true); GTween.killTweensOf(currentItem); - currentItem.tween( + currentItem!.tween( duration: .3, scale: bigSizeScale, onUpdate: positionItems, diff --git a/example/lib/demos/feeling_switch/scene.dart b/example/lib/demos/feeling_switch/scene.dart index fe1e2c4..856240e 100644 --- a/example/lib/demos/feeling_switch/scene.dart +++ b/example/lib/demos/feeling_switch/scene.dart @@ -2,13 +2,13 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; class FeelingSwitch extends GSprite { - double get sw => stage.stageWidth; + double get sw => stage!.stageWidth; - double get sh => stage.stageHeight; + double get sh => stage!.stageHeight; @override void addedToStage() { - stage.color = const Color(0xffF7F7F7); + stage!.color = const Color(0xffF7F7F7); var container = GSprite(); var tw = 100.0; var th = 40.0; @@ -100,7 +100,7 @@ class FeelingSwitch extends GSprite { toggle(); }); - stage.onResized.add(() { + stage!.onResized.add(() { var sc = sw / tw; container.scale = sc; container.setPosition(sw / 2, sh / 2); diff --git a/example/lib/demos/flower_gradient/scene.dart b/example/lib/demos/flower_gradient/scene.dart index 893c64c..44d8bf2 100644 --- a/example/lib/demos/flower_gradient/scene.dart +++ b/example/lib/demos/flower_gradient/scene.dart @@ -10,7 +10,7 @@ class FlowerScene extends GSprite { void createFlower() { var flower = GSprite(); addChild(flower); - flower.setPosition(stage.stageWidth / 2, stage.stageHeight / 2); + flower.setPosition(stage!.stageWidth / 2, stage!.stageHeight / 2); var numLines = 8; @@ -28,7 +28,7 @@ class FlowerScene extends GSprite { shape.name = 's$i'; var color1 = Colors.primaries[i % Colors.primaries.length]; - var color2 = Color.lerp(color1, Colors.black, .4); + var color2 = Color.lerp(color1, Colors.black, .4)!; shape.graphics.beginGradientFill( GradientType.linear, diff --git a/example/lib/demos/gauge_meter/gauge_scene.dart b/example/lib/demos/gauge_meter/gauge_scene.dart index 489fac0..63a3e72 100644 --- a/example/lib/demos/gauge_meter/gauge_scene.dart +++ b/example/lib/demos/gauge_meter/gauge_scene.dart @@ -6,20 +6,20 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; class GaugeMeterScene extends GSprite { - GSprite container; - GShape nailMeter; - GText labelValue; + late GSprite container; + late GShape nailMeter; + late GText labelValue; double swipeAngle = Math.PI * .8; - double offsetAngle; + late double offsetAngle; Color nailColor = Colors.redAccent; String letterValue = 'A'; int gaugeSteps = 7; double maxValue = 90; - double stepValueDeg; + late double stepValueDeg; - double get sw => stage.stageWidth; + double get sw => stage!.stageWidth; - double get sh => stage.stageHeight; + double get sh => stage!.stageHeight; @override void addedToStage() { @@ -34,7 +34,7 @@ class GaugeMeterScene extends GSprite { var curve = GShape(); container.addChild(curve); var bigRadius = 214 / 2; - final baseColor = Color.lerp(nailColor, Colors.black, .6); + final baseColor = Color.lerp(nailColor, Colors.black, .6)!; offsetAngle = -(Math.PI / 2) - swipeAngle / 2; var g = curve.graphics; @@ -94,7 +94,7 @@ class GaugeMeterScene extends GSprite { // big value text. var labelA = GText( - text: letterValue ?? 'V', + text: letterValue, textStyle: TextStyle( fontSize: 25, fontWeight: FontWeight.bold, @@ -136,8 +136,8 @@ class GaugeMeterScene extends GSprite { // adjust size // container.scale = .5; // container.$debugBounds = true; - stage.onResized.add(() { - var graphBounds = container.bounds; + stage!.onResized.add(() { + var graphBounds = container.bounds!; var r1 = sw / sh; var r2 = graphBounds.width / graphBounds.height; if (r1 < r2) { diff --git a/example/lib/demos/globe_3d/scene.dart b/example/lib/demos/globe_3d/scene.dart index 6abea19..3c85cd5 100644 --- a/example/lib/demos/globe_3d/scene.dart +++ b/example/lib/demos/globe_3d/scene.dart @@ -4,10 +4,10 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; class Globe3dScene extends GSprite { - List vertices; - List uvData; - List indices; - GSprite world; + late List vertices; + late List uvData; + late List indices; + late GSprite world; double centerZ = 500; int cols = 20, rows = 20; double fl = 1000; @@ -72,6 +72,7 @@ class Globe3dScene extends GSprite { } world.graphics.clear(); world.graphics.beginFill(Colors.black38); + /// TODO: fix issues with z ordering. // world.graphics.beginBitmapFill(texture); world.graphics.lineStyle(0, Color(0xffff00ff)); @@ -88,7 +89,7 @@ class Globe3dScene extends GSprite { @override void update(double delta) { super.update(delta); - world.setPosition(stage.stageWidth / 2, stage.stageHeight / 2); + world.setPosition(stage!.stageWidth / 2, stage!.stageHeight / 2); draw(); } } diff --git a/example/lib/demos/glowing_circle/glowing_scene.dart b/example/lib/demos/glowing_circle/glowing_scene.dart index ab7fdda..00a0c66 100644 --- a/example/lib/demos/glowing_circle/glowing_scene.dart +++ b/example/lib/demos/glowing_circle/glowing_scene.dart @@ -11,7 +11,7 @@ extension MyGlowingExt on Widget { double endScaleInterval = 0.8, double circleInterval = .2, double replayDelay = .2, - Function(Graphics graphics, Size size) graphicBuilder, + Function(Graphics graphics, Size size)? graphicBuilder, }) { return SceneBuilderWidget( builder: () => SceneController( @@ -34,7 +34,7 @@ class MyGlowingEffect extends GSprite { final Color color; final double duration, circleInterval, replayDelay; final double startScale, endScale, endScaleInterval; - final Function(Graphics graphics, Size size) graphicBuilder; + final Function(Graphics graphics, Size size)? graphicBuilder; MyGlowingEffect({ this.color = const Color(0x8842A5F5), @@ -56,8 +56,8 @@ class MyGlowingEffect extends GSprite { final circles = List.generate(4, (index) { var shape = GShape(); addChild(shape); - final size = Size(stage.stageWidth, stage.stageHeight); - shape.setPosition(stage.stageWidth / 2, stage.stageHeight / 2); + final size = Size(stage!.stageWidth, stage!.stageHeight); + shape.setPosition(stage!.stageWidth / 2, stage!.stageHeight / 2); if (graphicBuilder == null) { drawCircle(shape.graphics, size, color); } else { diff --git a/example/lib/demos/heart_reaction/scene.dart b/example/lib/demos/heart_reaction/scene.dart index 51177de..6135161 100644 --- a/example/lib/demos/heart_reaction/scene.dart +++ b/example/lib/demos/heart_reaction/scene.dart @@ -1,17 +1,16 @@ import 'package:graphx/graphx.dart'; -import '../../utils/svg_utils.dart'; import '../../utils/utils.dart'; import 'assets.dart'; class HeartScene extends GSprite { HeartScene({this.key}); - double get h => stage.stageHeight; + double get h => stage!.stageHeight; - double get w => stage.stageWidth; - SvgData svg; - final GlobalKey key; + double get w => stage!.stageWidth; + SvgData? svg; + final GlobalKey? key; @override Future addedToStage() async { @@ -21,7 +20,7 @@ class HeartScene extends GSprite { } void _heartRain() { - final _grect = ContextUtils.getRenderObjectBounds(key.currentContext); + final _grect = ContextUtils.getRenderObjectBounds(key!.currentContext!)!; var isUp = _grect.y < h / 2; var maxDuration = 0.0; List.generate( diff --git a/example/lib/demos/isma_chart/data.dart b/example/lib/demos/isma_chart/data.dart index c57b3f6..39cb034 100644 --- a/example/lib/demos/isma_chart/data.dart +++ b/example/lib/demos/isma_chart/data.dart @@ -13,7 +13,7 @@ final valueTextStyle = TextStyle( fontWeight: FontWeight.w600, ); -List cfrData; +late List cfrData; Future loadJson() async { // var id = 'assets/isma_chart/chart_data.json'; @@ -29,7 +29,7 @@ void buildData() { } class DotDataModel { - double value; + double? value; String year = '2020'; String value2 = '11'; String name = 'Ismail'; diff --git a/example/lib/demos/isma_chart/scene/chart_cell.dart b/example/lib/demos/isma_chart/scene/chart_cell.dart index d4dfad3..55c4cf3 100644 --- a/example/lib/demos/isma_chart/scene/chart_cell.dart +++ b/example/lib/demos/isma_chart/scene/chart_cell.dart @@ -1,4 +1,3 @@ - import 'dart:ui'; import 'package:flutter/material.dart'; @@ -7,11 +6,11 @@ import 'package:graphx/graphx.dart'; import '../data.dart'; class ChartTableCell extends GSprite { - double w, h; + double w = 0.0, h = 0.0; double cellH = 12; - double cellW; + late double cellW; - ChartTableCell([GSprite doc]) { + ChartTableCell([GSprite? doc]) { doc?.addChild(this); } @@ -40,7 +39,7 @@ class ChartTableCell extends GSprite { } } - void initDraw({double w, double h}) { + void initDraw({required double w, required double h}) { this.w = w; this.h = h; graphics diff --git a/example/lib/demos/isma_chart/scene/chart_scene.dart b/example/lib/demos/isma_chart/scene/chart_scene.dart index 0d2d65d..14c7a52 100644 --- a/example/lib/demos/isma_chart/scene/chart_scene.dart +++ b/example/lib/demos/isma_chart/scene/chart_scene.dart @@ -7,21 +7,21 @@ import 'chart_cell.dart'; import 'chart_sprite.dart'; class ChartScene extends GSprite { - GSprite boxCFR1; - GSprite boxCFR2; - ChartTableCell boxCell; - Chart boxLineChart; + late GSprite boxCFR1; + late GSprite boxCFR2; + late ChartTableCell boxCell; + late Chart boxLineChart; - double get sw => stage.stageWidth; + double get sw => stage!.stageWidth; - double get sh => stage.stageHeight; + double get sh => stage!.stageHeight; - double get chartH => stage.stageHeight - monthYearBarH; + double get chartH => stage!.stageHeight - monthYearBarH; double monthYearBarH = 26; - GText cfr1; - GText monthYear; - GSprite cfr2; + late GText cfr1; + late GText monthYear; + late GSprite cfr2; double valuesYW = 17; @@ -97,7 +97,7 @@ class ChartScene extends GSprite { boxLineChart.x = boxCell.x; } - GSprite valuesYContainer; + late GSprite valuesYContainer; void _buildYValues() { valuesYContainer = GSprite(); diff --git a/example/lib/demos/isma_chart/scene/chart_sprite.dart b/example/lib/demos/isma_chart/scene/chart_sprite.dart index a8b9f24..1d017ba 100644 --- a/example/lib/demos/isma_chart/scene/chart_sprite.dart +++ b/example/lib/demos/isma_chart/scene/chart_sprite.dart @@ -4,23 +4,23 @@ import 'package:graphx/graphx.dart'; import 'dot_button.dart'; class Chart extends GSprite { - double w, h; - int cols, rows; - GShape chartLine; + double w = 0.0, h = 0.0; + int cols = 0, rows = 0; + late GShape chartLine; - Chart([GSprite doc]) { + Chart([GSprite? doc]) { doc?.addChild(this); chartLine = GShape(); addChild(chartLine); } - double rowsSep; + double? rowsSep; void initDraw({ - double w, - double h, - int cols, - int rows, + required double w, + required double h, + int cols = 0, + int rows = 0, // double rowsSep, }) { this.w = w; @@ -35,8 +35,8 @@ class Chart extends GSprite { _drawGrid(); } - double maxValueY; - double colSep, rowSep, colOffset; + late double maxValueY; + double colSep = 0.0, rowSep = 0.0, colOffset = 0.0; void _drawGrid() { colSep = w / cols; diff --git a/example/lib/demos/isma_chart/scene/dot_button.dart b/example/lib/demos/isma_chart/scene/dot_button.dart index 36c3b54..25f830e 100644 --- a/example/lib/demos/isma_chart/scene/dot_button.dart +++ b/example/lib/demos/isma_chart/scene/dot_button.dart @@ -1,17 +1,16 @@ - import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; import '../data.dart'; class DotButton extends GSprite { - GShape bg, bgOver; + late GShape bg, bgOver; - DotDataModel model; + DotDataModel? model; void setValue(double value) { model = DotDataModel(); - model.value = value; + model!.value = value; } @override @@ -42,8 +41,8 @@ class DotButton extends GSprite { onMouseOver.add((event) { bgOver.tween(duration: .5, scale: 2); - final rect = bg.getBounds(stage); - model.coordinate.setTo( + final rect = bg.getBounds(stage)!; + model!.coordinate.setTo( rect.x + rect.width / 2, rect.y + rect.height / 2, ); diff --git a/example/lib/demos/jelly_thing/scene.dart b/example/lib/demos/jelly_thing/scene.dart index b4861d7..40c51fe 100644 --- a/example/lib/demos/jelly_thing/scene.dart +++ b/example/lib/demos/jelly_thing/scene.dart @@ -12,31 +12,30 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; class JellyDotsScene extends GSprite { - List points; + List? points; int totalPoints = 120; double size = 18; double mouseRadius = 80.0, mouseStrength = .06, stiffness = .05; bool outlineJelly = false; - double get sw => stage.stageWidth; + double get sw => stage!.stageWidth; - double get sh => stage.stageHeight; + double get sh => stage!.stageHeight; void _toggleVisible(Dot d) => d.visible = !d.visible; @override void addedToStage() { - stage.keyboard.onDown.add((event) { + stage!.keyboard!.onDown.add((event) { if (event.isKey(LogicalKeyboardKey.keyD)) { - points.forEach(_toggleVisible); + points!.forEach(_toggleVisible); } else if (event.isKey(LogicalKeyboardKey.keyO)) { outlineJelly = !outlineJelly; } else if (event.isKey(LogicalKeyboardKey.keyR)) { - for (var dot in points) { + for (var dot in points!) { dot.x = dot.px = dot.ox; dot.y = dot.py = dot.oy; dot.vx = dot.vy = 0; - } } }); @@ -63,7 +62,7 @@ class JellyDotsScene extends GSprite { @override void update(double delta) { super.update(delta); - if (stage.pointer.isDown) { + if (stage!.pointer!.isDown) { size = 20; stiffness = .15; } else { @@ -71,13 +70,13 @@ class JellyDotsScene extends GSprite { stiffness = .05; } for (var i = 0; i < totalPoints - 1; ++i) { - var p0 = points[i]; + var p0 = points![i]; for (var j = i + 1; j < totalPoints; ++j) { - var p1 = points[j]; + var p1 = points![j]; compare(p0, p1, j == i + 1); } } - compare(points[totalPoints - 1], points[0], true); + compare(points![totalPoints - 1], points![0], true); updatePoints(); draw(graphics); } @@ -86,7 +85,7 @@ class JellyDotsScene extends GSprite { /// save touch coordinates, to avoid the matrix transformation. var mx = mouseX; var my = mouseY; - for (var dot in points) { + for (var dot in points!) { var dx = dot.x - mx; var dy = dot.y - my; var dist = Math.sqrt(dx * dx + dy * dy); @@ -138,15 +137,15 @@ class JellyDotsScene extends GSprite { } /// get the middle points to get a smooth cubic bezier... - var pa = points[0]; - var pz = points.last; + var pa = points![0]; + var pz = points!.last; var mid1x = (pz.x + pa.x) / 2; var mid1y = (pz.y + pa.y) / 2; g.moveTo(mid1x, mid1y); - for (var i = 0; i < points.length - 1; ++i) { - var p0 = points[i]; - var p1 = points[i + 1]; + for (var i = 0; i < points!.length - 1; ++i) { + var p0 = points![i]; + var p1 = points![i + 1]; g.curveTo( p0.x, p0.y, @@ -163,10 +162,10 @@ class JellyDotsScene extends GSprite { /// dot (point) reference. class Dot extends GShape { - double ox, oy; - double px, py, vx = 0, vy = 0, friction = .9; + double ox = 0, oy = 0; + double px = 0, py = 0, vx = 0, vy = 0, friction = .9; - Dot({this.px, this.py}) { + Dot({required this.px, required this.py}) { graphics .beginFill(Colors.yellowAccent) .lineStyle(2, Colors.green.withOpacity(.5)) diff --git a/example/lib/demos/lined_button/scene.dart b/example/lib/demos/lined_button/scene.dart index 89fe2e6..b614c26 100644 --- a/example/lib/demos/lined_button/scene.dart +++ b/example/lib/demos/lined_button/scene.dart @@ -8,28 +8,28 @@ final stageColor = Colors.grey.shade800; class LinedButtonScene extends GSprite { @override void addedToStage() { - stage.color = stageColor; + stage!.color = stageColor; var btn = LineButton(120, 60); addChild(btn); - btn.x = stage.stageWidth / 2; - btn.y = stage.stageHeight / 2; + btn.x = stage!.stageWidth / 2; + btn.y = stage!.stageHeight / 2; } } class LineButton extends GSprite { double w, h; - Path _oriPath; - PathMetric _metrics; + late Path _oriPath; + late PathMetric _metrics; final _tweenTf = 0.0.twn; final _tweenBg1 = 0.0.twn; final _tweenBg2 = 0.0.twn; final _stageColorTween = stageColor.twn; - GShape bg; - GShape bg2; - GShape bgBounds; - GText tf; + late GShape bg; + late GShape bg2; + late GShape bgBounds; + GText? tf; bool isOver = false; LineButton([this.w = 100, this.h = 50]) { @@ -62,10 +62,10 @@ class LineButton extends GSprite { addChild(bg); addChild(bg2); addChild(bgBounds); - addChild(tf); + addChild(tf!); // mouseChildren = false; - tf.mouseEnabled = bg.mouseEnabled = bg2.mouseEnabled = false; + tf!.mouseEnabled = bg.mouseEnabled = bg2.mouseEnabled = false; // bgBounds.mouseUseShape = false; bgBounds.mouseEnabled = true; bgBounds.useCursor = true; @@ -73,9 +73,9 @@ class LineButton extends GSprite { bgBounds.onMouseDown.add((e) { GTween.killTweensOf(tf); GTween.killTweensOf(_openLink); - tf.tween(duration: .3, scale: .88); - stage.onMouseUp.addOnce((e) { - tf.tween( + tf!.tween(duration: .3, scale: .88); + stage!.onMouseUp.addOnce((e) { + tf!.tween( duration: .5, scale: 1, ease: GEase.elasticOut, @@ -94,8 +94,8 @@ class LineButton extends GSprite { }); }); alignPivot(); - tf.alignPivot(); - tf.setPosition(w / 2, h / 2); + tf!.alignPivot(); + tf!.setPosition(w / 2, h / 2); } void _openLink() { @@ -117,7 +117,7 @@ class LineButton extends GSprite { enters ? Colors.grey.shade900 : stageColor, ease: GEase.easeOutSine, duration: 1.1, - onUpdate: () => stage.color = _stageColorTween.value, + onUpdate: () => stage!.color = _stageColorTween.value, ); _tweenTf.tween(value, duration: .4, onUpdate: _drawText); @@ -136,12 +136,12 @@ class LineButton extends GSprite { } void _setStyle({ - FontWeight fontWeight, - double letterSpacing, - Color color, - double fontSize, + FontWeight? fontWeight, + double? letterSpacing, + Color? color, + double? fontSize, }) { - tf.setTextStyle( + tf!.setTextStyle( TextStyle( fontWeight: fontWeight, fontSize: fontSize, @@ -181,6 +181,6 @@ class LineButton extends GSprite { color: Colors.white, fontSize: 18, ); - tf.alignPivot(); + tf!.alignPivot(); } } diff --git a/example/lib/demos/lungs/scene.dart b/example/lib/demos/lungs/scene.dart index 7668db4..b09323e 100644 --- a/example/lib/demos/lungs/scene.dart +++ b/example/lib/demos/lungs/scene.dart @@ -1,4 +1,3 @@ -import 'package:exampleGraphx/utils/svg_utils.dart'; import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; @@ -38,7 +37,7 @@ class LungsScene extends GSprite { traquea.y = traquea.pivotY; double totalDuration = 2; - var baseY = stage.stageHeight / 2; + var baseY = stage!.stageHeight / 2; bool isExpanded = false; void _twnTrackea() { @@ -94,8 +93,8 @@ class LungsScene extends GSprite { lung.alignPivot(); lung.setPosition( - stage.stageWidth / 2, - stage.stageHeight / 2, + stage!.stageWidth / 2, + stage!.stageHeight / 2, ); } } diff --git a/example/lib/demos/mouse_repulsion/scene.dart b/example/lib/demos/mouse_repulsion/scene.dart index 1ad864b..fd0b5c1 100644 --- a/example/lib/demos/mouse_repulsion/scene.dart +++ b/example/lib/demos/mouse_repulsion/scene.dart @@ -8,14 +8,14 @@ class MouseRepulsionScene extends GSprite { var dots = []; double spring = .015, stiff = .02, damp = .95, radius = 150.0; - double radiusSq; + late double radiusSq; - double xoffset, yoffset; - GSprite container; - GShape mouseRadiusShape; + double? xoffset, yoffset; + late GSprite container; + late GShape mouseRadiusShape; - double get sw => stage.stageWidth; - double get sh => stage.stageHeight; + double get sw => stage!.stageWidth; + double get sh => stage!.stageHeight; @override void addedToStage() { @@ -34,8 +34,8 @@ class MouseRepulsionScene extends GSprite { var total = cols * rows; dots = List.generate(total, (index) { var d = GraphPoint(); - var idx = index % cols ?? 0; - var idy = index ~/ cols ?? 0; + var idx = index % cols; + var idy = index ~/ cols; if (index == 0) { d.tx = d.x = 0; d.ty = d.y = 0; @@ -62,7 +62,7 @@ class MouseRepulsionScene extends GSprite { container.x = (sw - cols * sep) / 2; container.y = (sh - rows * sep) / 2; - if (stage.pointer.isDown) { + if (stage!.pointer!.isDown) { radius = 60; } else { radius = 150; diff --git a/example/lib/demos/murat_coffee/scene.dart b/example/lib/demos/murat_coffee/scene.dart index bd6707a..89432e6 100644 --- a/example/lib/demos/murat_coffee/scene.dart +++ b/example/lib/demos/murat_coffee/scene.dart @@ -9,7 +9,7 @@ class CoffeeItemScene extends GSprite { var product = _ProductSerious(); // product = _ProductPlayful(); product.loadImage(imageUrl); - product.setPosition(stage.stageWidth / 4, 0); + product.setPosition(stage!.stageWidth / 4, 0); addChild(product); } } @@ -30,9 +30,9 @@ class _ProductSerious extends _ProductPlayful { } class _ProductPlayful extends GSprite { - String url; - GBitmap image; - GShape shadow; + late String url; + late GBitmap image; + late GShape shadow; double shadowY = 0.0; double imageY = 0.0; @@ -57,8 +57,8 @@ class _ProductPlayful extends GSprite { ..graphics.beginFill(kColorBlack).drawCircle(0, 0, itmW / 2).endFill(); shadow.filters = [GBlurFilter(8, 8)]; shadow.scaleY = .2; - shadowY = shadow.y = image.bounds.height + shadow.height; - shadow.x = image.bounds.width / 2; + shadowY = shadow.y = image.bounds!.height + shadow.height; + shadow.x = image.bounds!.width / 2; addChild(image); addChild(shadow); diff --git a/example/lib/demos/nico_loading_indicator/scene.dart b/example/lib/demos/nico_loading_indicator/scene.dart index 7694d41..37ef363 100644 --- a/example/lib/demos/nico_loading_indicator/scene.dart +++ b/example/lib/demos/nico_loading_indicator/scene.dart @@ -6,7 +6,7 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; class CustomLoadingIndicator extends StatelessWidget { - const CustomLoadingIndicator({Key key}) : super(key: key); + const CustomLoadingIndicator({Key? key}) : super(key: key); @override Widget build(BuildContext context) { @@ -17,8 +17,8 @@ class CustomLoadingIndicator extends StatelessWidget { } class CustomLoadingIndicatorSprite extends GSprite { - GShape fillSquare; - GSprite corners; + late GShape fillSquare; + late GSprite corners; static const expandTo = 60.0; static const colapseTo = 45.0; @@ -36,9 +36,9 @@ class CustomLoadingIndicatorSprite extends GSprite { @override void addedToStage() { - stage.onResized.add((){ - x = stage.stageWidth / 2; - y = stage.stageHeight / 2; + stage!.onResized.add((){ + x = stage!.stageWidth / 2; + y = stage!.stageHeight / 2; }); corners = GSprite(); @@ -88,7 +88,7 @@ class CustomLoadingIndicatorSprite extends GSprite { } void positionCorners() { - final size = currentSize / 2; + final size = currentSize! / 2; corners.children[0].x = -size; corners.children[0].y = -size; @@ -119,5 +119,5 @@ class CustomLoadingIndicatorSprite extends GSprite { addChild(fillSquare); } - double get currentSize => _currentSizeCorner.value; + double? get currentSize => _currentSizeCorner.value; } diff --git a/example/lib/demos/nokia_snake/game_page_widget.dart b/example/lib/demos/nokia_snake/game_page_widget.dart index 95a4b67..ae85960 100644 --- a/example/lib/demos/nokia_snake/game_page_widget.dart +++ b/example/lib/demos/nokia_snake/game_page_widget.dart @@ -9,7 +9,7 @@ import 'nokia_snake.dart'; class GamePage extends StatefulWidget { final int speed; - const GamePage({Key key, @required this.speed}) : super(key: key); + const GamePage({Key? key, required this.speed}) : super(key: key); @override _GamePageState createState() => _GamePageState(); diff --git a/example/lib/demos/nokia_snake/game_scene.dart b/example/lib/demos/nokia_snake/game_scene.dart index 08a63fa..d017b5e 100644 --- a/example/lib/demos/nokia_snake/game_scene.dart +++ b/example/lib/demos/nokia_snake/game_scene.dart @@ -13,11 +13,11 @@ class SnakeGameScene extends GSprite { GRect foodRect = GRect(); - double get sw => stage.stageWidth ?? 0; + double get sw => stage!.stageWidth; - double get sh => stage.stageHeight ?? 0; + double get sh => stage!.stageHeight; - GText scoreSt; + late GText scoreSt; final List> snake = >[ [0, 0], [0, 0], @@ -41,7 +41,7 @@ class SnakeGameScene extends GSprite { @override void addedToStage() { // stage.color = boardBackground; - stage.maskBounds = true; + stage!.maskBounds = true; mps.on('RESET', gameOver); mps.on('COMMAND', changeState); scoreSt = GText.build( @@ -55,7 +55,7 @@ class SnakeGameScene extends GSprite { scoreSt.setPosition(20.0, 20.0); generateFood(); resetSnake(); - stage.keyboard.onDown.add(onKeyDown); + stage!.keyboard!.onDown.add(onKeyDown); } @override @@ -194,20 +194,20 @@ class SnakeGameScene extends GSprite { } void _togglePause() { - if (stage.controller.ticker.isTicking) { + if (stage!.controller.ticker!.isTicking) { scoreSt.text = 'PAUSED'; - stage.controller.ticker.callNextFrame(() { - stage.controller.ticker.pause(); + stage!.controller.ticker!.callNextFrame(() { + stage!.controller.ticker!.pause(); }); } else { _updateScore(); - stage.controller.ticker.resume(); + stage!.controller.ticker!.resume(); } mps.publish1('Score', scoreSt.text); } void onKeyDown(KeyboardEventData event) { - final key = event.rawEvent.logicalKey; + final key = event.rawEvent!.logicalKey; if (key == Keys.LEFT_KEY) { changeState(SnakeCommands.left); } @@ -249,7 +249,7 @@ class SnakeGameScene extends GSprite { } } - void changeState([SnakeCommands command]) { + void changeState([SnakeCommands? command]) { if (command == SnakeCommands.pause) { _togglePause(); } diff --git a/example/lib/demos/nokia_snake/mobile_button_widget.dart b/example/lib/demos/nokia_snake/mobile_button_widget.dart index 344e3a5..666e3d9 100644 --- a/example/lib/demos/nokia_snake/mobile_button_widget.dart +++ b/example/lib/demos/nokia_snake/mobile_button_widget.dart @@ -4,12 +4,12 @@ import 'package:flutter/rendering.dart'; class MobileControlButton extends StatelessWidget { const MobileControlButton({ - Key key, + Key? key, this.icon, this.onPressed, }) : super(key: key); - final IconData icon; - final Function onPressed; + final IconData? icon; + final Function? onPressed; MobileControlButton.left(this.onPressed) : icon = Icons.keyboard_arrow_left_outlined; @@ -28,7 +28,7 @@ class MobileControlButton extends StatelessWidget { return MouseRegion( cursor: SystemMouseCursors.click, child: GestureDetector( - onTap: onPressed, + onTap: onPressed as void Function()?, child: CircleAvatar( backgroundColor: Theme.of(context).accentColor.withOpacity(.4), child: Icon( diff --git a/example/lib/demos/nokia_snake/nokia_snake.dart b/example/lib/demos/nokia_snake/nokia_snake.dart index 028ea37..5538a34 100644 --- a/example/lib/demos/nokia_snake/nokia_snake.dart +++ b/example/lib/demos/nokia_snake/nokia_snake.dart @@ -11,7 +11,7 @@ import 'package:graphx/graphx.dart'; import 'game_page_widget.dart'; class NokiaSnakeMain extends StatefulWidget { - const NokiaSnakeMain({Key key}) : super(key: key); + const NokiaSnakeMain({Key? key}) : super(key: key); @override _NokiaSnakeMainState createState() => _NokiaSnakeMainState(); @@ -85,7 +85,7 @@ class _NokiaSnakeMainState extends State { }, trailing: PopupMenuButton( initialValue: speed, - onSelected: (value) => setState(() { + onSelected: (dynamic value) => setState(() { speed = value; }), itemBuilder: (_) => levels diff --git a/example/lib/demos/page_indicator/dot.dart b/example/lib/demos/page_indicator/dot.dart index 2633c4e..1d8dd08 100644 --- a/example/lib/demos/page_indicator/dot.dart +++ b/example/lib/demos/page_indicator/dot.dart @@ -6,38 +6,38 @@ import 'package:graphx/graphx.dart'; class PageDot extends GShape { int id; - double _baseSize; + double? _baseSize; - Color _color; + Color? _color; - Color get color => _color; + Color? get color => _color; - set color(Color value) { + set color(Color? value) { if (value == _color) return; _color = value; _invalidateDraw(); } - Color _targetColor; + Color? _targetColor; - Color get targetColor => _targetColor; + Color? get targetColor => _targetColor; - GTweenableColor _colorTween; + GTweenableColor? _colorTween; bool _invalidColor = false; - set targetColor(Color value) { + set targetColor(Color? value) { if (value == _color) return; _targetColor = value; _invalidColor = true; } - double _size; - double targetSize; + double? _size; + double? targetSize; - double get size => _size; + double get size => _size!; set size(double value) { - if (value < _baseSize) value = _baseSize; + if (value < _baseSize!) value = _baseSize!; if (value == _size) return; _size = value; _invalidateDraw(); @@ -53,8 +53,8 @@ class PageDot extends GShape { void _draw() { graphics .clear() - .beginFill(_color) - .drawRoundRect(0, 0, _size, _baseSize, _baseSize / 2) + .beginFill(_color!) + .drawRoundRect(0, 0, _size!, _baseSize!, _baseSize! / 2) .endFill(); } @@ -107,9 +107,9 @@ class PageDot extends GShape { if (_colorTween != null) { GTween.killTweensOf(_colorTween); } - _colorTween = _color.twn; - _colorTween.tween(_targetColor, duration: .3, onUpdate: () { - color = _colorTween.value; + _colorTween = _color!.twn; + _colorTween!.tween(_targetColor!, duration: .3, onUpdate: () { + color = _colorTween!.value; }); } } diff --git a/example/lib/demos/page_indicator/scene.dart b/example/lib/demos/page_indicator/scene.dart index 7dab822..4b29b73 100644 --- a/example/lib/demos/page_indicator/scene.dart +++ b/example/lib/demos/page_indicator/scene.dart @@ -10,7 +10,7 @@ import 'dot.dart'; class PageIndicatorPaged extends BaseScene { PageIndicatorPaged(); - List _dots; + late List _dots; static const double dotSize = 13; static const double dotPreW = 18; static const double dotSelectedW = 34; @@ -18,8 +18,8 @@ class PageIndicatorPaged extends BaseScene { static const dotSelectedColor = Colors.red; static const dotPreColor = Colors.blue; - GSprite container; - GSprite scrollContainer; + late GSprite container; + late GSprite scrollContainer; int _currentIndex = 0; final int _visibleItems = 5; @@ -76,8 +76,8 @@ class PageIndicatorPaged extends BaseScene { /// -- end masking. /// only for testing. - stage.keyboard.focusNode.requestFocus(); - stage.keyboard.onDown.add((event) { + stage!.keyboard!.focusNode.requestFocus(); + stage!.keyboard!.onDown.add((event) { if (event.arrowLeft) { moveDir(-1); } else if (event.arrowRight) { @@ -85,7 +85,7 @@ class PageIndicatorPaged extends BaseScene { } }); - stage.onResized.add(() { + stage!.onResized.add(() { var ratioScale = sw / _allDotsWidth; scale = ratioScale; @@ -155,17 +155,17 @@ class PageIndicatorPaged extends BaseScene { /// the expensize "colorize". nextDot?.targetColor = dotPreColor; prevDot?.targetColor = dotPreColor; - currDot?.targetSize = dotSelectedW; - currDot?.targetColor = dotSelectedColor; + currDot.targetSize = dotSelectedW; + currDot.targetColor = dotSelectedColor; } void _layoutDots() { var lastX = 0.0; for (var i = 0; i < _dots.length; ++i) { var dot = _dots[i]; - var sizeDistance = dot.targetSize - dot.size; + var sizeDistance = dot.targetSize! - dot.size; if (sizeDistance.abs() < .1) { - dot.size = dot.targetSize; + dot.size = dot.targetSize!; } else { dot.size += sizeDistance / dotSizeEase; } @@ -183,12 +183,12 @@ class PageIndicatorPaged extends BaseScene { return _dots[_currentIndex]; } - PageDot get prevDot { + PageDot? get prevDot { if (_currentIndex == 0) return null; return _dots[_currentIndex - 1]; } - PageDot get nextDot { + PageDot? get nextDot { if (_currentIndex >= _numItems - 1) return null; return _dots[_currentIndex + 1]; } diff --git a/example/lib/demos/path_chart_stress/scene.dart b/example/lib/demos/path_chart_stress/scene.dart index cf80996..1a893ef 100644 --- a/example/lib/demos/path_chart_stress/scene.dart +++ b/example/lib/demos/path_chart_stress/scene.dart @@ -20,15 +20,15 @@ class PathChartScene extends GSprite { var label = section.label; var idx = colors.indexOf(c); if (idx == 0) { - addChild(label); + addChild(label!); label.x = 30; label.y = 80 + 20.0 * idx; } }); - container.x = stage.stageWidth * .8; - container.y = stage.stageHeight * .5; - stage.onEnterFrame.add((event) { + container.x = stage!.stageWidth * .8; + container.y = stage!.stageHeight * .5; + stage!.onEnterFrame.add((event) { // if (container.width > container.x + 100) { // tw = container.x + 100; // container.width = tw; @@ -70,7 +70,7 @@ class ChartSection extends GShape { // List.generate(19, (index) => addSlot()); } - GText label; + GText? label; int frameCount = 0; double targetX = 0; Path maskPath = Path(); @@ -82,7 +82,7 @@ class ChartSection extends GShape { label = GText.build( text: 'color', color: color, fontSize: 14, fontWeight: FontWeight.bold); - stage.onEnterFrame.add((event) { + stage!.onEnterFrame.add((event) { if (++frameCount % 3 == 0) { addSlot(); pivotX = width; @@ -107,7 +107,7 @@ class ChartSection extends GShape { void addSlot() { ++numQuads; - label.text = '$numQuads rects'; + label!.text = '$numQuads rects'; graphics.clear(); graphics.beginFill(color.withOpacity(.3)); graphics.lineStyle(2, color); diff --git a/example/lib/demos/pie_chart/scene.dart b/example/lib/demos/pie_chart/scene.dart index 825af35..a8e9a1e 100644 --- a/example/lib/demos/pie_chart/scene.dart +++ b/example/lib/demos/pie_chart/scene.dart @@ -14,7 +14,7 @@ class PieChartScene extends GSprite { lineContainer.mouseChildren = false; lineContainer.mouseEnabled = false; - var sw2 = stage.stageWidth / 2; + var sw2 = stage!.stageWidth / 2; var numPieces = 5; var data = List.generate(numPieces, (index) => Math.randomRange(10, 50)); var total = data.reduce((value, element) => value + element); @@ -23,11 +23,11 @@ class PieChartScene extends GSprite { var totalRad = deg2rad(360); var currentAngle = 0.0; - GSprite currentPiece; + GSprite? currentPiece; for (var i = 0; i < numPieces; ++i) { var color = Colors.primaries[(i) % Colors.primaries.length].value; var color1 = Color(color); - var color2 = Color.lerp(color1, Colors.black, .8); + var color2 = Color.lerp(color1, Colors.black, .8)!; var percent = data[i] / total; var myAngle = percent * totalRad; var pieceLine = GSprite(); @@ -54,22 +54,22 @@ class PieChartScene extends GSprite { piece.userData = pieceLine; piece.mouseChildren = false; piece.onMouseOver.add((e) { - GDisplayObject line; + GDisplayObject? line; if (currentPiece != null) { - line = currentPiece.userData as GDisplayObject; + line = currentPiece!.userData as GDisplayObject?; GTween.killTweensOf(currentPiece); GTween.killTweensOf(line); - currentPiece.tween(duration: .35, scale: 1, ease: GEase.easeInBack); - line.tween(duration: .35, scale: 1, ease: GEase.easeInBack); + currentPiece!.tween(duration: .35, scale: 1, ease: GEase.easeInBack); + line!.tween(duration: .35, scale: 1, ease: GEase.easeInBack); } // var p = e.target; currentPiece = piece; - line = currentPiece.userData as GDisplayObject; + line = currentPiece!.userData as GDisplayObject?; // e.target.scale = 1.4; GTween.killTweensOf(line); GTween.killTweensOf(piece); piece.tween(duration: .35, scale: .9, ease: GEase.easeOutExpo); - line.tween(duration: .35, scale: .9, ease: GEase.easeOutExpo); + line!.tween(duration: .35, scale: .9, ease: GEase.easeOutExpo); }); var percentText = (percent * 100.0).toStringAsPrecision(2); @@ -115,6 +115,6 @@ class PieChartScene extends GSprite { extension MyObject on GDisplayObject { void centerInStage() { if (!inStage) return; - setPosition(stage.stageWidth / 2, stage.stageHeight / 2); + setPosition(stage!.stageWidth / 2, stage!.stageHeight / 2); } } diff --git a/example/lib/demos/pizza_box/scene.dart b/example/lib/demos/pizza_box/scene.dart index 52593ce..f0b669f 100644 --- a/example/lib/demos/pizza_box/scene.dart +++ b/example/lib/demos/pizza_box/scene.dart @@ -4,20 +4,19 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; class PizzaBoxScene extends GSprite { + double get sw => stage!.stageWidth; + double get sh => stage!.stageHeight; - double get sw => stage.stageWidth; - double get sh => stage.stageHeight; - - GBitmap pizza; - GSprite container, pizzaContainer; + late GBitmap pizza; + late GSprite container, pizzaContainer; double boxS = 80; bool isOpen = true; - GShape sideTop, sideBottom; - GTexture pizzaTexture; + late GShape sideTop, sideBottom; + GTexture? pizzaTexture; @override void addedToStage() async { - stage.color = Colors.grey.shade50; + stage!.color = Colors.grey.shade50; pizzaTexture = await ResourceLoader.loadTexture('assets/pizza_box/pizza.png', 2); run(); diff --git a/example/lib/demos/raster_draw/scene.dart b/example/lib/demos/raster_draw/scene.dart index 771e2a0..4bf9399 100644 --- a/example/lib/demos/raster_draw/scene.dart +++ b/example/lib/demos/raster_draw/scene.dart @@ -3,9 +3,9 @@ import 'package:graphx/graphx.dart'; import '../../utils/utils.dart'; class DrawingScene extends GSprite { - GShape drawer; - GSprite container; - GBitmap captured; + late GShape drawer; + late GSprite container; + late GBitmap captured; @override void addedToStage() { @@ -15,7 +15,7 @@ class DrawingScene extends GSprite { /// capturing the snapshot. container.graphics .beginFill(Colors.red.withOpacity(0)) - .drawRect(0, 0, stage.stageWidth, stage.stageHeight) + .drawRect(0, 0, stage!.stageWidth, stage!.stageHeight) .endFill(); drawer = GShape(); captured = GBitmap(); @@ -28,13 +28,13 @@ class DrawingScene extends GSprite { container.addChild(drawer); /// keep the stage clipped to the Widget size. - stage.maskBounds = true; + stage!.maskBounds = true; /// shows a border around the stage area (for debug). - stage.showBoundsRect = true; + stage!.showBoundsRect = true; /// listen to mouse/touch events. - stage.onMouseDown.add(_onDown); + stage!.onMouseDown.add(_onDown); } /// basic draw line command from the previous point. @@ -52,7 +52,7 @@ class DrawingScene extends GSprite { /// refresh the GBitmap with the new texture. captured.texture = texture; - stage.onMouseMove.remove(_onMove); + stage!.onMouseMove.remove(_onMove); /// after capturing the Texture, we clear the drawn line... to start fresh. /// and not overload the CPU. @@ -67,7 +67,7 @@ class DrawingScene extends GSprite { kColorBlack.withOpacity(Math.randomRange(.4, 1)), ); drawer.graphics.moveTo(mouseX, mouseY); - stage.onMouseMove.add(_onMove); - stage.onMouseUp.addOnce(_onRelease); + stage!.onMouseMove.add(_onMove); + stage!.onMouseUp.addOnce(_onRelease); } } diff --git a/example/lib/demos/rating_star/scene/rating_scene.dart b/example/lib/demos/rating_star/scene/rating_scene.dart index 344d990..5427e0b 100644 --- a/example/lib/demos/rating_star/scene/rating_scene.dart +++ b/example/lib/demos/rating_star/scene/rating_scene.dart @@ -8,15 +8,15 @@ const Color kStarColor = Color(0xFFFCC915); const Color kUnselectedSColor = Color(0xFF7F86AC); class RatingStarsScene extends GSprite { - double get sw => stage.stageWidth; + double get sw => stage!.stageWidth; - double get sh => stage.stageHeight; - List stars; - GSprite container; + double get sh => stage!.stageHeight; + late List stars; + late GSprite container; @override void addedToStage() { - stage.color = kBgColor; + stage!.color = kBgColor; container = GSprite(); addChild(container); stars = List.generate( @@ -35,7 +35,7 @@ class RatingStarsScene extends GSprite { }, ); container.alignPivot(); - final bb = container.bounds; + final bb = container.bounds!; container.graphics.beginFill(kColorTransparent).drawGRect(bb).endFill(); container.onMouseOut.add((event) { if (container.hitTouch(GPoint( @@ -46,7 +46,7 @@ class RatingStarsScene extends GSprite { stars[i].hoverState(false); } }); - stage.onResized.add(() { + stage!.onResized.add(() { container.setPosition(sw / 2, sh / 2); }); } diff --git a/example/lib/demos/rating_star/scene/star.dart b/example/lib/demos/rating_star/scene/star.dart index 1d32036..7c48f09 100644 --- a/example/lib/demos/rating_star/scene/star.dart +++ b/example/lib/demos/rating_star/scene/star.dart @@ -8,19 +8,19 @@ class Star extends GSprite { double dotSize = 10; bool active = false; - GShape _star; + late GShape _star; - GSprite _broken; + GSprite? _broken; - GShape _dot; + late GShape _dot; Star() { _initUi(); mouseChildren = false; } - static GTexture _tx1; - static GTexture _tx2; + static GTexture? _tx1; + static GTexture? _tx2; Future createTemplate() async { var st = GShape(); @@ -77,7 +77,7 @@ class Star extends GSprite { await createTemplate(); } _broken = GSprite(); - addChild(_broken); + addChild(_broken!); var bmp1 = GBitmap(_tx1); var bmp2 = GBitmap(_tx2); // bmp1.nativePaint.filterQuality = FilterQuality.medium; @@ -86,18 +86,18 @@ class Star extends GSprite { bmp1.pivotY = 24; bmp2.pivotX = 11; bmp2.pivotY = 24; - _broken.addChild(bmp1); - _broken.addChild(bmp2); - _broken.visible = false; + _broken!.addChild(bmp1); + _broken!.addChild(bmp2); + _broken!.visible = false; /// manual adjustment. - _broken.pivotX = bmp2.pivotX - 3; - _broken.pivotY = -3; + _broken!.pivotX = bmp2.pivotX - 3; + _broken!.pivotY = -3; } _handleDown(e) { if (!_selected) return; - stage.onMouseUp.addOnce(_handleUp); + stage!.onMouseUp.addOnce(_handleUp); _star.tween(duration: .24, scale: .86, overwrite: 0); } @@ -119,14 +119,14 @@ class Star extends GSprite { final _color = kUnselectedSColor.withAlpha(0); - _broken.setProps( + _broken!.setProps( y: 0, alpha: 1, visible: true, colorize: _color, ); - var p1 = _broken.children[0]; - var p2 = _broken.children[1]; + var p1 = _broken!.children[0]; + var p2 = _broken!.children[1]; p1.setProps(rotation: 0, y: 0); p2.setProps(rotation: 0, y: 0); @@ -144,7 +144,7 @@ class Star extends GSprite { ease: GEase.easeOutQuad, ); - _broken.tween( + _broken!.tween( duration: .3, delay: .1, colorize: kUnselectedSColor, @@ -152,13 +152,13 @@ class Star extends GSprite { ); var blur = GBlurFilter(0, 0); - _broken.filters = [blur]; + _broken!.filters = [blur]; var a = 0.0.twn; a.tween(8, duration: .5, delay: .16, onUpdate: () { blur.blurY = blur.blurX = a.value; }); - _broken.tween( + _broken!.tween( duration: .6, overwrite: 0, y: 50, @@ -167,7 +167,7 @@ class Star extends GSprite { alpha: 0, ease: GEase.easeInCubic, onComplete: () { - _broken.visible = false; + _broken!.visible = false; _star.visible = false; }, ); @@ -179,7 +179,7 @@ class Star extends GSprite { ); } else { GTween.killTweensOf(_broken); - _broken.visible = false; + _broken!.visible = false; _star.setProps(y: 0, rotation: 0, scale: 0, visible: true); _dot.tween(duration: .6, scale: 0); _star.tween( diff --git a/example/lib/demos/run_hero_canvas/scene/hero_scene.dart b/example/lib/demos/run_hero_canvas/scene/hero_scene.dart index 4fe3e74..e1df437 100644 --- a/example/lib/demos/run_hero_canvas/scene/hero_scene.dart +++ b/example/lib/demos/run_hero_canvas/scene/hero_scene.dart @@ -6,20 +6,20 @@ import 'package:graphx/graphx.dart'; class PainterRawScene extends GSprite { @override Future addedToStage() async { - stage.color = Colors.black; - stage.maskBounds = true; + stage!.color = Colors.black; + stage!.maskBounds = true; /// load assets! await _loadAssets(); addChild(ParallaxView()); - stage.keyboard.onDown.add((e) { + stage!.keyboard!.onDown.add((e) { if (e.isKey(LogicalKeyboardKey.space)) { mps.emit('jump'); } }); - stage.onMouseDown.add((event) { + stage!.onMouseDown.add((event) { mps.emit('jump'); }); } @@ -33,7 +33,10 @@ class PainterRawScene extends GSprite { await ResourceLoader.loadTexture( 'assets/run_hero/parallax/layer_03.png', 2, 'l3'); await ResourceLoader.loadTexture( - 'assets/run_hero/parallax/layer_04.png', 2, 'l4',); + 'assets/run_hero/parallax/layer_04.png', + 2, + 'l4', + ); await ResourceLoader.loadGif( 'assets/run_hero/run_outline.gif', resolution: 1, @@ -48,13 +51,13 @@ class PainterRawScene extends GSprite { } class ParallaxView extends GDisplayObjectContainer { - List layers = []; + List layers = []; List matrices = []; List paintings = []; final jumpY = 0.0.twn; int heroFrame = 0; - GifAtlas hero; + GifAtlas? hero; final gradientPaint = Paint(); final heroPaint = Paint(); @@ -90,11 +93,11 @@ class ParallaxView extends GDisplayObjectContainer { @override void addedToStage() { gradientPaint.blendMode = BlendMode.color; - final gradCenter = Offset(stage.stageWidth / 2, stage.stageHeight / 2); + final gradCenter = Offset(stage!.stageWidth / 2, stage!.stageHeight / 2); final gradMatrix = Matrix4.identity()..scale(.9); gradientPaint.shader = ui.Gradient.radial( gradCenter, - stage.stageWidth, + stage!.stageWidth, [Colors.red.withOpacity(.3), Colors.blue.withOpacity(1)], [0.1, .9], TileMode.clamp, @@ -105,9 +108,9 @@ class ParallaxView extends GDisplayObjectContainer { void heroState(String id) => hero = ResourceLoader.getGif(id); @override - void $applyPaint(Canvas canvas) { - canvas.save(); - canvas.scale(1 / (layers[0].scale)); + void $applyPaint(Canvas? canvas) { + canvas!.save(); + canvas.scale(1 / layers[0]!.scale!); matrices[0].translate(-.5); matrices[1].translate(-.8); matrices[2].translate(-3.0); @@ -125,7 +128,7 @@ class ParallaxView extends GDisplayObjectContainer { void drawLayer(Canvas canvas, int index) { paintings[index].shader = ImageShader( - layers[index].root, + layers[index]!.root!, TileMode.repeated, TileMode.mirror, matrices[index].storage, @@ -135,9 +138,9 @@ class ParallaxView extends GDisplayObjectContainer { void drawHero(Canvas canvas) { if (++heroFrame % 4 == 0) { - hero.nextFrame(); + hero!.nextFrame(); } - var img = hero.root; + var img = hero!.root!; // heroPaint.invertColors = true; // heroPaint.blendMode = BlendMode.colorDodge; var heroScale = 2.0; @@ -145,7 +148,7 @@ class ParallaxView extends GDisplayObjectContainer { canvas.save(); canvas.translate(300.0, floorY); canvas.scale(heroScale); - canvas.translate(-hero.width / 2, -hero.height); + canvas.translate(-hero!.width! / 2, -hero!.height!); canvas.drawImage(img, Offset(0, 0), heroPaint); canvas.restore(); } diff --git a/example/lib/demos/simple_interactions/simple_interactions_scene.dart b/example/lib/demos/simple_interactions/simple_interactions_scene.dart index 71e6e23..9f13ee4 100644 --- a/example/lib/demos/simple_interactions/simple_interactions_scene.dart +++ b/example/lib/demos/simple_interactions/simple_interactions_scene.dart @@ -5,7 +5,7 @@ import 'package:graphx/graphx.dart'; import 'ui/my_button.dart'; class SimpleInteractionsScene extends GSprite { - GShape ball; + late GShape ball; @override void addedToStage() { @@ -18,9 +18,9 @@ class SimpleInteractionsScene extends GSprite { /// internally. // button.onMouseDown.add((e) => print("mouse down on button! $e")); - stage.onResized.add(() { - button.x = stage.stageWidth / 2; - button.y = stage.stageHeight / 2; + stage!.onResized.add(() { + button.x = stage!.stageWidth / 2; + button.y = stage!.stageHeight / 2; }); _initBall(); @@ -38,8 +38,8 @@ class SimpleInteractionsScene extends GSprite { ball.x = 100; ball.y = 100; - stage.keyboard.onDown.add(_onKeyboardDown); - stage.keyboard.onUp.add(_onKeyboardUp); + stage!.keyboard!.onDown.add(_onKeyboardDown); + stage!.keyboard!.onUp.add(_onKeyboardUp); } /// Only the stage has access to keyboard events. @@ -55,7 +55,7 @@ class SimpleInteractionsScene extends GSprite { /// for access modifiers keys, is better to check the raw event itself. /// as multiple physical keys have the same behaviour (shift, command, /// alt, etc) but different key codes. - if (event.rawEvent.isShiftPressed) { + if (event.rawEvent!.isShiftPressed) { pixelsToMove = 30.0; } @@ -71,7 +71,7 @@ class SimpleInteractionsScene extends GSprite { if (event.isKey(LogicalKeyboardKey.arrowUp)) { // arrow key UP ball.y -= pixelsToMove; - } else if (event.rawEvent.logicalKey == LogicalKeyboardKey.arrowDown) { + } else if (event.rawEvent!.logicalKey == LogicalKeyboardKey.arrowDown) { // arrow key DOWN ball.y += pixelsToMove; } diff --git a/example/lib/demos/simple_interactions/ui/my_button.dart b/example/lib/demos/simple_interactions/ui/my_button.dart index 893614b..041e2c0 100644 --- a/example/lib/demos/simple_interactions/ui/my_button.dart +++ b/example/lib/demos/simple_interactions/ui/my_button.dart @@ -1,5 +1,4 @@ import 'package:flutter/material.dart'; -import 'package:flutter_icons/flutter_icons.dart'; import 'package:graphx/graphx.dart'; class MyButton extends GSprite { @@ -8,19 +7,19 @@ class MyButton extends GSprite { double h = 80; // backwards background (black) - GShape bg; + late GShape bg; // filled background that changes with [_fillPercent] (yellow) - GShape fillBg; + late GShape fillBg; // the light bulb icon that toggles when clicking the button - GIcon icon; + GIcon icon = GIcon(Icons.ac_unit); bool _isTouching = false; bool _isOn = false; double _fillPercent = 0.0; - GText _fillText; + late GText _fillText; MyButton() { _init(); @@ -35,7 +34,6 @@ class MyButton extends GSprite { fillBg = GShape(); _dragBackground(fillBg.graphics, Colors.yellow.shade800); - icon = GIcon(null); _updateIcon(); icon.alignPivot(); @@ -104,7 +102,7 @@ class MyButton extends GSprite { /// Handler for pointer down (mouse or touch). void _onMouseDown(MouseInputData input) { scale = .94; - stage.onMouseUp.addOnce(_onStageRelease); + stage!.onMouseUp.addOnce(_onStageRelease); } /// Handler for mouse scroll wheel (only desktop). @@ -155,10 +153,10 @@ class MyButton extends GSprite { /// update the [icon.data] and icon's color, based on [_isOn] current state. void _updateIcon() { if (_isOn) { - icon.data = Feather.sun; + icon.data = Icons.brightness_7_outlined; icon.color = Colors.yellow; } else { - icon.data = Feather.moon; + icon.data = Icons.brightness_2_outlined; icon.color = Colors.white; } } diff --git a/example/lib/demos/simple_radial_menu/circ_menu.dart b/example/lib/demos/simple_radial_menu/circ_menu.dart index 09bd7d3..df376d9 100644 --- a/example/lib/demos/simple_radial_menu/circ_menu.dart +++ b/example/lib/demos/simple_radial_menu/circ_menu.dart @@ -36,14 +36,14 @@ class SimpleRadialMenuScene extends GSprite { var container = GSprite(); addChild(container); - items?.clear(); + items.clear(); var mainCircle = createCircle( label: 'MAIN', size: itemSize * 1.5, iconData: Icons.menu, onPressed: toggleMenu, ); - container.setPosition(stage.stageWidth / 2, stage.stageHeight / 2); + container.setPosition(stage!.stageWidth / 2, stage!.stageHeight / 2); var numItems = icons.length; var angleStep = Math.PI * 2 / numItems; var angleOffset = -Math.PI / 2; @@ -68,10 +68,10 @@ class SimpleRadialMenuScene extends GSprite { } GSprite createCircle({ - String label, - double size, - IconData iconData, - Function(MouseInputData input) onPressed, + String? label, + required double size, + required IconData iconData, + Function(MouseInputData input)? onPressed, }) { var item = GSprite(); var text = GText( @@ -114,11 +114,11 @@ class SimpleRadialMenuScene extends GSprite { isOpen = !isOpen; for (var i = 0; i < items.length; ++i) { final itm = items[i]; - var point = itm.userData as GPoint; + var point = itm.userData as GPoint?; itm.tween( duration: .3, - x: isOpen ? point.x : 0, - y: isOpen ? point.y : 0, + x: isOpen ? point!.x : 0, + y: isOpen ? point!.y : 0, ); // itm.x = isOpen ? point.x : 0; // itm.y = isOpen ? point.y : 0; diff --git a/example/lib/demos/simple_shape/simple_shapes_scene.dart b/example/lib/demos/simple_shape/simple_shapes_scene.dart index 8b5a098..cac5422 100644 --- a/example/lib/demos/simple_shape/simple_shapes_scene.dart +++ b/example/lib/demos/simple_shape/simple_shapes_scene.dart @@ -2,7 +2,7 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; class SimpleShapesScene extends GSprite { - GShape triangle; + late GShape triangle; @override void addedToStage() { diff --git a/example/lib/demos/simple_toast/simple_toast.dart b/example/lib/demos/simple_toast/simple_toast.dart index 139b448..aba105b 100644 --- a/example/lib/demos/simple_toast/simple_toast.dart +++ b/example/lib/demos/simple_toast/simple_toast.dart @@ -18,8 +18,8 @@ class SimpleToastMain extends StatelessWidget { } class MyHomePage extends StatefulWidget { - MyHomePage({Key key, this.title}) : super(key: key); - final String title; + MyHomePage({Key? key, this.title}) : super(key: key); + final String? title; @override _MyHomePageState createState() => _MyHomePageState(); @@ -27,7 +27,7 @@ class MyHomePage extends StatefulWidget { class _MyHomePageState extends State { int _counter = 0; - double bottom; + double? bottom; final tec = TextEditingController(); void _incrementCounter() { @@ -56,7 +56,7 @@ class _MyHomePageState extends State { // sendKeyboardOpenEvent(); return Scaffold( appBar: AppBar( - title: Text(widget.title), + title: Text(widget.title!), ), body: Center( child: Column( diff --git a/example/lib/demos/simple_toast/toast.dart b/example/lib/demos/simple_toast/toast.dart index 62fff4a..8195d0f 100644 --- a/example/lib/demos/simple_toast/toast.dart +++ b/example/lib/demos/simple_toast/toast.dart @@ -6,13 +6,13 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; class ToastScene extends GSprite { - GSprite container; - GShape bg; - GSprite button; - GShape buttonGShape; - GText text; - GText buttonText; - GIcon myIcon; + late GSprite container; + late GShape bg; + late GSprite button; + late GShape buttonGShape; + late GText text; + late GText buttonText; + late GIcon myIcon; @override void addedToStage() { @@ -27,7 +27,7 @@ class ToastScene extends GSprite { .drawRoundRect( 0, 0, - stage.stageWidth - 20, + stage!.stageWidth - 20, 60, 10, ) @@ -43,7 +43,7 @@ class ToastScene extends GSprite { final paragraphStyle = ParagraphStyle(maxLines: 2, ellipsis: '...'); text = GText( text: '', - width: stage.stageWidth - 150, + width: stage!.stageWidth - 150, paragraphStyle: paragraphStyle, textStyle: TextStyle(fontSize: 18, color: Colors.white), ) @@ -51,7 +51,7 @@ class ToastScene extends GSprite { ..y = 13; buttonText = GText( text: 'Increment', - width: stage.stageWidth - 150, + width: stage!.stageWidth - 150, paragraphStyle: paragraphStyle, textStyle: TextStyle(fontSize: 14, color: Colors.white), ) @@ -60,7 +60,7 @@ class ToastScene extends GSprite { addChild(container); container ..x = 10 - ..y = stage.stageHeight + 20 + ..y = stage!.stageHeight + 20 ..addChild(bg) ..addChild(text) ..addChild(myIcon) @@ -71,9 +71,9 @@ class ToastScene extends GSprite { void _onShowSnackbar(Map value) { text.text = value['text']; bg.colorize = value['color']; - bg.width = stage.stageWidth - 20; + bg.width = stage!.stageWidth - 20; button - ..x = stage.stageWidth - 120 + ..x = stage!.stageWidth - 120 ..y = 10 ..onMouseClick(value['onMouseClick']); @@ -82,7 +82,7 @@ class ToastScene extends GSprite { void _changeSnackDirection(double bottom) { final open = bottom != 0; - if (container.y <= stage.stageHeight) { + if (container.y <= stage!.stageHeight) { if (open) { show(bottom); } else { @@ -92,7 +92,7 @@ class ToastScene extends GSprite { } void show(double bottom) { - var targetY = (stage.stageHeight - container.height - 10) - bottom; + var targetY = (stage!.stageHeight - container.height - 10) - bottom; container.tween( y: targetY, duration: 1, @@ -111,7 +111,7 @@ class ToastScene extends GSprite { container.tween( duration: 1, ease: GEase.elasticIn, - y: stage.stageHeight + 20, + y: stage!.stageHeight + 20, ); GTween.delayedCall(.8, () { bg.tween( diff --git a/example/lib/demos/simple_tween/simple_tween.dart b/example/lib/demos/simple_tween/simple_tween.dart index 606855d..c1f738c 100644 --- a/example/lib/demos/simple_tween/simple_tween.dart +++ b/example/lib/demos/simple_tween/simple_tween.dart @@ -69,7 +69,7 @@ class _TweenMenu extends StatelessWidget { ); } - Widget _addButton({String label, IconData icon, VoidCallback onPressed}) { + Widget _addButton({required String label, IconData? icon, VoidCallback? onPressed}) { return TextButton( // color: Colors.red, child: Row( diff --git a/example/lib/demos/simple_tween/simple_tween_scene.dart b/example/lib/demos/simple_tween/simple_tween_scene.dart index d9a64f8..c4a9d00 100644 --- a/example/lib/demos/simple_tween/simple_tween_scene.dart +++ b/example/lib/demos/simple_tween/simple_tween_scene.dart @@ -7,21 +7,21 @@ import 'tween_controller.dart'; class SimpleTweenScene extends GSprite { final TweenSceneController controller; - MyBox box; - GSprite centeredContainer; + MyBox? box; + late GSprite centeredContainer; SimpleTweenScene(this.controller); @override void addedToStage() { /// we can colorize the background of the scene. - stage.color = Colors.grey.shade300; + stage!.color = Colors.grey.shade300; /// by default the Canvas drawing in Flutter has no "masking", you can paint /// anywhere on the screen (outside the stage size ). /// so to know which area is available to us, we can mask the stage, like /// culling, all objects outside the stage size, will not be visible. - stage.maskBounds = true; + stage!.maskBounds = true; /// use this Sprite to keep the box always centered in the stage. centeredContainer = GSprite(); @@ -30,13 +30,13 @@ class SimpleTweenScene extends GSprite { /// add the box as child of the container (will inherit all the /// transformations from the parent). - centeredContainer.addChild(box); + centeredContainer.addChild(box!); // add the container to the root scene. addChild(centeredContainer); /// now the box is drawn from the top left corner drawRect(0,0,width,height) /// so we can change the pivots so it centers itself in the parent - box.alignPivot(Alignment.center); + box!.alignPivot(Alignment.center); controller.onRotate.add(_rotateBox); controller.onScale.add(_scaleBox); @@ -46,10 +46,10 @@ class SimpleTweenScene extends GSprite { _initCounter(); /// listen for stage resize events. - stage.onResized.add(_onStageResize); + stage!.onResized.add(_onStageResize); } - GText counterText; + late GText counterText; /// There's support for several native types in GTween. /// double, int, Map, List, DisplayObject, GxPoint, GxRect.. @@ -87,13 +87,13 @@ class SimpleTweenScene extends GSprite { void _moveBox(int dir) { if (dir == 0) { - box.tween(duration: .5, x: 0, ease: GEase.elasticOut); + box!.tween(duration: .5, x: 0, ease: GEase.elasticOut); } else { final relativeMove = 10.0 * dir; /// using Strings we can tween any value relative to the current value /// of the object. - box.tween(duration: .5, x: '$relativeMove'); + box!.tween(duration: .5, x: '$relativeMove'); } } @@ -101,19 +101,19 @@ class SimpleTweenScene extends GSprite { /// kill any running tweens on `box` GTween.killTweensOf(box); - box.tween( + box!.tween( duration: 1, scaleX: 2, ease: GEase.bounceOut, ); - box.tween( + box!.tween( duration: 1, scaleY: 3, delay: .4, ease: GEase.bounceOut, onComplete: () { - box.tween( + box!.tween( duration: .4, scale: 1, // scale modifies scaleX, scaleY proportionally. ease: GEase.easeOutBack, @@ -125,12 +125,12 @@ class SimpleTweenScene extends GSprite { /// kill any running tweens on `box` GTween.killTweensOf(box); - box.tween( + box!.tween( duration: 1.5, rotation: Math.PI_2, // radians, or use `deg2rad(360)` ease: GEase.easeInOutExpo, onComplete: () { - box.tween( + box!.tween( duration: .5, rotation: 0, // radians, or use `deg2rad(360)` ease: GEase.easeOutBack, @@ -142,8 +142,8 @@ class SimpleTweenScene extends GSprite { void _onStageResize() { /// center in the Stage. centeredContainer.setPosition( - stage.stageWidth / 2, - stage.stageHeight / 2, + stage!.stageWidth / 2, + stage!.stageHeight / 2, ); } } diff --git a/example/lib/demos/sorting_button/scene/root_scene.dart b/example/lib/demos/sorting_button/scene/root_scene.dart index 6c3e20b..0c2f399 100644 --- a/example/lib/demos/sorting_button/scene/root_scene.dart +++ b/example/lib/demos/sorting_button/scene/root_scene.dart @@ -1,4 +1,5 @@ import 'package:exampleGraphx/utils/utils.dart'; + /// roipeker 2021 /// just wrap ur app with this, to emit "global" events (and close the dropdown) @@ -9,8 +10,8 @@ import 'package:exampleGraphx/utils/utils.dart'; import 'package:graphx/graphx.dart'; class RootWidget extends StatelessWidget { - final Widget child; - const RootWidget({Key key, this.child}) : super(key: key); + final Widget? child; + const RootWidget({Key? key, this.child}) : super(key: key); @override Widget build(BuildContext context) { @@ -24,15 +25,15 @@ class RootWidget extends StatelessWidget { class RootScene extends GSprite { @override void dispose() { - stage?.onMouseDown?.removeAll(); + stage?.onMouseDown.removeAll(); mps.offAll('windowMouseDown'); super.dispose(); } @override void addedToStage() { - stage.onMouseDown.add((event) { - mps.emit1('windowMouseDown', event.rawEvent.windowPosition); + stage!.onMouseDown.add((event) { + mps.emit1('windowMouseDown', event.rawEvent!.windowPosition); }); } } diff --git a/example/lib/demos/sorting_button/scene/sorting_button_scene.dart b/example/lib/demos/sorting_button/scene/sorting_button_scene.dart index 8102e8b..ab167b9 100644 --- a/example/lib/demos/sorting_button/scene/sorting_button_scene.dart +++ b/example/lib/demos/sorting_button/scene/sorting_button_scene.dart @@ -8,27 +8,27 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; class SortingButtonScene extends GSprite { - double get sw => stage.stageWidth; + double get sw => stage!.stageWidth; - double get sh => stage.stageHeight; + double get sh => stage!.stageHeight; @override void dispose() { - stage?.onMouseDown?.removeAll(); + stage?.onMouseDown.removeAll(); super.dispose(); } @override void addedToStage() { - stage.color = const Color(0xffdededede); + stage!.color = const Color(0xffdededede); var btn = SortingButton(195, 50); /// as we need to detect global touches on the window, we listen the event /// from a "root" scene on top of MaterialApp. var lastPress = 0; - stage.onMouseDown.add((event) { + stage!.onMouseDown.add((event) { lastPress = getTimer(); - if (!btn.bounds.containsPoint(btn.mousePosition)) { + if (!btn.bounds!.containsPoint(btn.mousePosition)) { if (btn.isOpen) btn.closeDropdown(); } }); @@ -52,18 +52,18 @@ class SortingButton extends GSprite { ]; double w, h; - GSprite options; - GShape bg, menuMask, clickArea; - GText label, sortBy; - GIcon arrow; + late GSprite options; + GShape? bg, menuMask, clickArea; + late GText label, sortBy; + late GIcon arrow; double labelPaddingX = 18; - double labelMaxW; + late double labelMaxW; bool isOpen = false; double optionH = 40; double optionSep = 0; - double menuOpenH; + late double menuOpenH; final tweenMenuSize = 0.0.twn; int _selectedIndex = -1; final highlighColor = const Color(0xff99979D); @@ -93,15 +93,15 @@ class SortingButton extends GSprite { menuMask = GShape(); bg = GShape(); clickArea = GShape(); - addChild(bg); - addChild(menuMask); - addChild(clickArea); + addChild(bg!); + addChild(menuMask!); + addChild(clickArea!); tweenMenuSize.value = h; - drawBackground(bg.graphics, h, 5, Colors.black); - drawBackground(menuMask.graphics, h, 5, Colors.black); - drawBackground(clickArea.graphics, h, 0, Colors.red.withOpacity(.4)); + drawBackground(bg!.graphics, h, 5, Colors.black); + drawBackground(menuMask!.graphics, h, 5, Colors.black); + drawBackground(clickArea!.graphics, h, 0, Colors.red.withOpacity(.4)); - clickArea.alpha = 0; + clickArea!.alpha = 0; arrow = GIcon(Icons.arrow_back_ios, Colors.white, 14); arrow.alignPivot(Alignment.centerLeft); @@ -132,14 +132,14 @@ class SortingButton extends GSprite { ); sortBy.mouseEnabled = false; arrow.mouseEnabled = - label.mouseEnabled = menuMask.mouseEnabled = bg.mouseEnabled = false; + label.mouseEnabled = menuMask!.mouseEnabled = bg!.mouseEnabled = false; options = GSprite(); addChild(options); options.y = h; options.mask = menuMask; _createOptions(); - clickArea.onMouseDown.add(_onMousePress); + clickArea!.onMouseDown.add(_onMousePress); _selectItem(0); } @@ -152,7 +152,7 @@ class SortingButton extends GSprite { } var offset = 14.0; - bg.tween( + bg!.tween( duration: .25, width: w + offset, height: h + offset, @@ -161,12 +161,12 @@ class SortingButton extends GSprite { ease: GEase.easeOutQuart, overwrite: 0, ); - stage.onMouseUp.addOnce(_onMouseUp); + stage!.onMouseUp.addOnce(_onMouseUp); } void _onMouseUp(MouseInputData event) { GTween.killTweensOf(_delayedOpen); - bg.tween( + bg!.tween( duration: 1.3, width: w, height: h, @@ -181,7 +181,7 @@ class SortingButton extends GSprite { void _delayedOpen() { GTween.killTweensOf(bg); - bg.setProps(scale: 1, x: 0, y: 0); + bg!.setProps(scale: 1, x: 0, y: 0); GTween.killTweensOf(tweenMenuSize); openDropdown(); } @@ -190,16 +190,16 @@ class SortingButton extends GSprite { if (_selectedIndex == idx) return; if (_selectedIndex > -1) { var o = items[_selectedIndex]; - var dot = o.getChildByName('dot'); - var label = o.getChildByName('label'); + var dot = o.getChildByName('dot')!; + var label = o.getChildByName('label')!; dot.tween(duration: .2, x: labelPaddingX / 2, alpha: 0); label.tween(duration: .2, x: labelPaddingX); } _selectedIndex = idx; if (_selectedIndex > -1) { var o = items[_selectedIndex]; - var dot = o.getChildByName('dot'); - var label = o.getChildByName('label'); + var dot = o.getChildByName('dot')!; + var label = o.getChildByName('label')!; dot.tween(duration: .4, x: labelPaddingX, alpha: 1); label.tween(duration: .4, x: labelPaddingX + 10); } @@ -223,13 +223,13 @@ class SortingButton extends GSprite { arrow.tween(duration: .6, alpha: 1, overwrite: 0); sortBy.tween(duration: .8, alpha: 1); _writeLabel(dataModel[_selectedIndex]); - bg.tween(duration: .4, y: 0); + bg!.tween(duration: .4, y: 0); }); /// make background bounce a few times. void _bounceBg() { - var ty = bg.y > 0 ? -1.5 : 3; - bg.tween( + var ty = bg!.y > 0 ? -1.5 : 3; + bg!.tween( duration: .16, y: ty, onComplete: _bounceBg, @@ -302,7 +302,7 @@ class SortingButton extends GSprite { }); itm.onMouseDown.add((event) { subBg.tween(duration: .3, alpha: .5); - stage.onMouseUp.addOnce((event) { + stage!.onMouseUp.addOnce((event) { if (event.dispatcher == itm) { subBg.tween(duration: .3, alpha: .25); _selectItem(i); @@ -337,8 +337,8 @@ class SortingButton extends GSprite { duration: .7, ease: GEase.fastLinearToSlowEaseIn, onUpdate: () { - drawBackground(bg.graphics, tweenMenuSize.value, 5); - drawBackground(menuMask.graphics, tweenMenuSize.value, 5); + drawBackground(bg!.graphics, tweenMenuSize.value, 5); + drawBackground(menuMask!.graphics, tweenMenuSize.value, 5); }, ); final len = items.length; @@ -357,7 +357,7 @@ class SortingButton extends GSprite { void openDropdown() { if (isOpen) return; isOpen = true; - bg.setProps(scale: 1, x: 0, y: 0); + bg!.setProps(scale: 1, x: 0, y: 0); arrow.tween( duration: .4, rotation: deg2rad(isOpen ? 90 : 360.0 - 90), @@ -369,8 +369,8 @@ class SortingButton extends GSprite { duration: 2, ease: GEase.fastLinearToSlowEaseIn, onUpdate: () { - drawBackground(bg.graphics, tweenMenuSize.value, 5); - drawBackground(menuMask.graphics, tweenMenuSize.value, 5); + drawBackground(bg!.graphics, tweenMenuSize.value, 5); + drawBackground(menuMask!.graphics, tweenMenuSize.value, 5); }, ); @@ -387,14 +387,14 @@ class SortingButton extends GSprite { } GText createLabel({ - String text, - double targetW, - double containerH, + String? text, + required double targetW, + double? containerH, double letterSpacing = 0.2, - double fontSize, + double? fontSize, Color color = Colors.white, FontWeight weight = FontWeight.w600, - GSprite doc, + GSprite? doc, }) { var tf = GText( text: text, diff --git a/example/lib/demos/spiral_loader/spiral_loader_scene.dart b/example/lib/demos/spiral_loader/spiral_loader_scene.dart index bceda80..1a6b0a0 100644 --- a/example/lib/demos/spiral_loader/spiral_loader_scene.dart +++ b/example/lib/demos/spiral_loader/spiral_loader_scene.dart @@ -2,12 +2,12 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; class DnaScene extends GSprite { - double spiralRadius, centerX, centerY, centerZ; + double spiralRadius = 0.0, centerX = 0.0, centerY = 0.0, centerZ = 0.0; double fl = 120; - List dots; - Bar bar; - GSprite container; + late List dots; + late Bar bar; + late GSprite container; double sizeCounter = 0; @override @@ -25,7 +25,7 @@ class DnaScene extends GSprite { bar = Bar(); container.addChild(bar); bar.x = 30; - container.y = stage.stageHeight / 2; + container.y = stage!.stageHeight / 2; } @override @@ -33,7 +33,7 @@ class DnaScene extends GSprite { super.update(delta); sizeCounter += delta; - centerX = stage.stageWidth / 2; + centerX = stage!.stageWidth / 2; centerY = 0; //stage.stageHeight / 2; centerZ = 160.0; bar.pz = centerZ; diff --git a/example/lib/demos/splash_intro/scene/logo_drawer.dart b/example/lib/demos/splash_intro/scene/logo_drawer.dart index b2e9160..a916719 100644 --- a/example/lib/demos/splash_intro/scene/logo_drawer.dart +++ b/example/lib/demos/splash_intro/scene/logo_drawer.dart @@ -12,17 +12,15 @@ import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:graphx/graphx.dart'; -import '../../../utils/svg_utils.dart'; - /// GSprite that will hold a SVG path drawing with a /// filled and outlined version... and the ability to partially /// draw the outlined based on percentage. class LogoDrawer extends GSprite { - List _metricsList; - Path _rootPath; + late List _metricsList; + late Path _rootPath; - GShape line; - GShape fill; + late GShape line; + late GShape fill; LogoDrawer() { _init(); @@ -53,11 +51,11 @@ class LogoDrawer extends GSprite { drawPercent(1); } - void drawPercent(double percent) { + void drawPercent(double? percent) { line.graphics.clear(); line.graphics.lineStyle(1, Colors.white); for (var m in _metricsList) { - line.graphics.drawPath(m.extractPath(0, m.length * percent)); + line.graphics.drawPath(m.extractPath(0, m.length * percent!)); } line.graphics.endFill(); } diff --git a/example/lib/demos/splash_intro/scene/splash_scene.dart b/example/lib/demos/splash_intro/scene/splash_scene.dart index 9ac1de9..f241540 100644 --- a/example/lib/demos/splash_intro/scene/splash_scene.dart +++ b/example/lib/demos/splash_intro/scene/splash_scene.dart @@ -18,22 +18,22 @@ abstract class DemoEvents { } class SplashScene extends GSprite { - GSprite logoContainer; - GShape splashCircle; - LogoDrawer graphxLogo, byLogo, roipekerLogo, flutterLogo; + GSprite? logoContainer; + late GShape splashCircle; + late LogoDrawer graphxLogo, byLogo, roipekerLogo, flutterLogo; @override void addedToStage() { visible = false; - stage.onResized.add(_handleStageResize); + stage!.onResized.add(_handleStageResize); mps.on(DemoEvents.reset, _showDemo); loadSvg(); } void _handleStageResize() { /// keep the logo centered. - logoContainer?.x = stage.stageWidth / 2; - logoContainer?.y = stage.stageHeight / 2; + logoContainer?.x = stage!.stageWidth / 2; + logoContainer?.y = stage!.stageHeight / 2; } void _showDemo() { @@ -41,12 +41,12 @@ class SplashScene extends GSprite { splashCircle.graphics.clear(); splashCircle.graphics.beginFill(Colors.redAccent); - splashCircle.graphics.drawCircle(0, 0, stage.stageWidth); + splashCircle.graphics.drawCircle(0, 0, stage!.stageWidth); splashCircle.graphics.endFill(); splashCircle.scale = 0; - stage.color = kColorTransparent; - stage.addChild(splashCircle); - splashCircle.setPosition(stage.stageWidth / 2, stage.stageHeight / 2); + stage!.color = kColorTransparent; + stage!.addChild(splashCircle); + splashCircle.setPosition(stage!.stageWidth / 2, stage!.stageHeight / 2); splashCircle.tween( duration: 1, @@ -64,7 +64,7 @@ class SplashScene extends GSprite { splashCircle = GShape(); logoContainer = GSprite(); - addChild(logoContainer); + addChild(logoContainer!); graphxLogo = await buildLogo(graphxSvgString); byLogo = await buildLogo(bySvgString); @@ -121,15 +121,15 @@ class SplashScene extends GSprite { roipekerLogo.line.visible = true; flutterLogo.line.visible = true; - logoContainer.alignPivot(); - logoContainer.x = stage.stageWidth / 2; - logoContainer.y = stage.stageHeight / 2; + logoContainer!.alignPivot(); + logoContainer!.x = stage!.stageWidth / 2; + logoContainer!.y = stage!.stageHeight / 2; } void _runDemo() { mps.emit1(DemoEvents.run, true); visible = true; - stage.color = Colors.redAccent; + stage!.color = Colors.redAccent; _resetObjects(); var t1 = 0.0.twn; var t2 = 0.0.twn; @@ -251,11 +251,11 @@ class SplashScene extends GSprite { void _showGlobalMask() { splashCircle.graphics.clear(); splashCircle.graphics.beginFill(Colors.white); - splashCircle.graphics.drawCircle(0, 0, stage.stageWidth); + splashCircle.graphics.drawCircle(0, 0, stage!.stageWidth); splashCircle.graphics.endFill(); - stage.addChild(splashCircle); + stage!.addChild(splashCircle); splashCircle.scale = 0.1; - splashCircle.setPosition(stage.stageWidth / 2, stage.stageHeight / 2); + splashCircle.setPosition(stage!.stageWidth / 2, stage!.stageHeight / 2); splashCircle.tween( duration: .45, scale: 1, @@ -268,8 +268,8 @@ class SplashScene extends GSprite { } void showFlutter() { - stage.addChild(splashCircle); - stage.color = kColorTransparent; + stage!.addChild(splashCircle); + stage!.color = kColorTransparent; splashCircle.tween( duration: .4, scale: 0, @@ -321,7 +321,7 @@ class SplashScene extends GSprite { Future buildLogo(String word) async { var logo = LogoDrawer(); await logo.parseSvg(word); - logoContainer.addChild(logo); + logoContainer!.addChild(logo); return logo; } } diff --git a/example/lib/demos/submit_button/scene/my_button.dart b/example/lib/demos/submit_button/scene/my_button.dart index 4a23a91..60c03b9 100644 --- a/example/lib/demos/submit_button/scene/my_button.dart +++ b/example/lib/demos/submit_button/scene/my_button.dart @@ -3,15 +3,15 @@ import 'package:graphx/graphx.dart'; class MyButton extends GSprite { double w, h; - GShape bg, border1, border2; - GIcon successIco; + late GShape bg, border1, border2; + late GIcon successIco; - GText label; + late GText label; final Color mainColor = const Color(0xff58A993); final Color greyColor = const Color(0xffE3E3E3); final tweenWidth = 0.0.twn; - double currentW; - double percentLoaded = 0.0; + double? currentW; + double? percentLoaded = 0.0; double lineThickness = 4; MyButton(this.w, this.h) { @@ -53,7 +53,7 @@ class MyButton extends GSprite { void _onMousePress(event) { bg.tween(duration: .3, colorize: mainColor); label.tween(duration: .2, colorize: Colors.white, scale: .9); - stage.onMouseUp.addOnce(_onMouseUp); + stage!.onMouseUp.addOnce(_onMouseUp); } void _onMouseUp(event) { @@ -85,7 +85,7 @@ class MyButton extends GSprite { void setToProgress() { percentLoaded = 0; - final tweenProgress = percentLoaded.twn; + final tweenProgress = percentLoaded!.twn; tweenProgress.tween( 1.0, duration: 1.3, @@ -138,7 +138,7 @@ class MyButton extends GSprite { border2.graphics .clear() .lineStyle(lineThickness, mainColor) - .arc(0, 0, radius, -Math.PI / 2, Math.PI_2 * percentLoaded) + .arc(0, 0, radius, -Math.PI / 2, Math.PI_2 * percentLoaded!) .endFill(); } @@ -146,22 +146,22 @@ class MyButton extends GSprite { bg.graphics .clear() .beginFill(Colors.white) - .drawRoundRect(-currentW / 2, -h / 2, currentW, h, h / 2) + .drawRoundRect(-currentW! / 2, -h / 2, currentW!, h, h / 2) .endFill(); var lineWOffset = lineThickness / 2; border1.graphics .clear() .beginFill(kColorTransparent) .drawRoundRect( - -currentW / 2 - lineWOffset, + -currentW! / 2 - lineWOffset, -h / 2 - lineWOffset, - currentW + lineWOffset * 2, + currentW! + lineWOffset * 2, h + lineWOffset * 2, h / 2, ) .endFill() .lineStyle(lineThickness, mainColor) - .drawRoundRect(-currentW / 2, -h / 2, currentW, h, h / 2) + .drawRoundRect(-currentW! / 2, -h / 2, currentW!, h, h / 2) .endFill(); bg.alignPivot(); border1.alignPivot(); diff --git a/example/lib/demos/submit_button/scene/scene.dart b/example/lib/demos/submit_button/scene/scene.dart index 43da541..9f81fce 100644 --- a/example/lib/demos/submit_button/scene/scene.dart +++ b/example/lib/demos/submit_button/scene/scene.dart @@ -7,7 +7,7 @@ import 'my_button.dart'; class SubmitButtonScene extends GSprite { @override void addedToStage() { - var btn = MyButton(stage.stageWidth, stage.stageHeight); + var btn = MyButton(stage!.stageWidth, stage!.stageHeight); addChild(btn); } } diff --git a/example/lib/demos/svg_icons/test_icons.dart b/example/lib/demos/svg_icons/test_icons.dart index 96fbe99..3bdf542 100644 --- a/example/lib/demos/svg_icons/test_icons.dart +++ b/example/lib/demos/svg_icons/test_icons.dart @@ -44,7 +44,7 @@ class TestIcons extends GSprite { begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [Colors.red, Colors.blue], - ).createShader(icon3.bounds.toNative()); + ).createShader(icon3.bounds!.toNative()); // take the bounding box from the icon. // GraphX has a nifty method to check bounding boxes. // icon3.$debugBounds = true; diff --git a/example/lib/demos/svg_icons/test_svg_scene.dart b/example/lib/demos/svg_icons/test_svg_scene.dart index ecd5432..098f860 100644 --- a/example/lib/demos/svg_icons/test_svg_scene.dart +++ b/example/lib/demos/svg_icons/test_svg_scene.dart @@ -2,15 +2,14 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; import '../../assets/svg_icons.dart'; -import '../../utils/svg_utils.dart'; class TestSvgScene extends GSprite { final groundHeight = 100.0; - GSprite trees, ground; + late GSprite trees, ground; @override void addedToStage() { - stage.color = Colors.lightBlueAccent.shade100; + stage!.color = Colors.lightBlueAccent.shade100; _init(); } @@ -23,8 +22,8 @@ class TestSvgScene extends GSprite { addChild(trees); addChild(ground); - trees.y = stage.stageHeight - groundHeight; - ground.y = stage.stageHeight - groundHeight; + trees.y = stage!.stageHeight - groundHeight; + ground.y = stage!.stageHeight - groundHeight; _drawTrees(); _drawGround(); @@ -35,9 +34,9 @@ class TestSvgScene extends GSprite { // add the sun. var sun = getSvgIcon(SvgId.cloudy); sun.alignPivot(); - sun.width = stage.stageWidth / 2; + sun.width = stage!.stageWidth / 2; sun.scaleY = sun.scaleX; - sun.setPosition(stage.stageWidth / 2, sun.height / 2); + sun.setPosition(stage!.stageWidth / 2, sun.height / 2); addChild(sun); } @@ -77,7 +76,7 @@ class TestSvgScene extends GSprite { // .beginFill(0xFFE477) // .beginFill(0xFCF2B6) .beginFill(Colors.green) - .drawRect(0, 0, stage.stageWidth, groundHeight) + .drawRect(0, 0, stage!.stageWidth, groundHeight) .endFill(); /// add some ground objects. @@ -86,7 +85,7 @@ class TestSvgScene extends GSprite { var obj = getSvgIcon(objectId); obj.alignPivot(Alignment.bottomCenter); obj.y = Math.randomRange(20, groundHeight); - obj.x = Math.randomRange(20, stage.stageWidth - 20); + obj.x = Math.randomRange(20, stage!.stageWidth - 20); obj.scale = Math.randomRange(.8, 1.5); if (objectId == SvgId.snail) { /// DisplayObjects has a userData property so u can save custom stuffs @@ -109,7 +108,7 @@ class TestSvgScene extends GSprite { /// if the snail is outside the stage area... move it to the /// other side of the screen. - if (snail.x > stage.stageWidth) { + if (snail.x > stage!.stageWidth) { snail.x = -100; } @@ -120,7 +119,7 @@ class TestSvgScene extends GSprite { onComplete: () => _tweenSnail(snail), ); - double originalScale = snail.userData; + double originalScale = snail.userData as double; /// scale down 80% snail.tween( @@ -144,7 +143,7 @@ class TestSvgScene extends GSprite { addChild(leaf); - var px = Math.randomRange(10, stage.stageWidth - 10); + var px = Math.randomRange(10, stage!.stageWidth - 10); leaf.setPosition(px, -10); final rndPivot = Math.randomBool() ? Alignment.bottomCenter : Alignment.topCenter; @@ -167,7 +166,7 @@ class TestSvgScene extends GSprite { } } - void _tweenLeaf({int dir, GDisplayObject leaf}) { + void _tweenLeaf({required int dir, required GDisplayObject leaf}) { final randomRotation = Math.randomRange(10, 45.0) * dir; final randomDuration = Math.randomRange(.75, 1); final randomSkew = Math.randomRange(.1, .3) * -dir; @@ -177,7 +176,7 @@ class TestSvgScene extends GSprite { skewX: randomSkew, skewY: -randomSkew / 2, onComplete: () { - if (leaf.y > stage.stageHeight) { + if (leaf.y > stage!.stageHeight) { print('Leaf outside of stage, remove and dispose it.'); leaf.removeFromParent(true); } else { diff --git a/example/lib/demos/trigrid/scene/scene.dart b/example/lib/demos/trigrid/scene/scene.dart index 0b81eb5..e8f3741 100644 --- a/example/lib/demos/trigrid/scene/scene.dart +++ b/example/lib/demos/trigrid/scene/scene.dart @@ -16,30 +16,30 @@ class DrawTriangleGridScene extends GSprite { double sep = 50 / res; int cols = 5 * res, rows = 4 * res; double spring = .0025, stiff = .02, damp = .98, radius = targetRadius; - double radiusSq; + late double radiusSq; - List dots; - TriangleGrid triGrid; - GSprite container; + late List dots; + TriangleGrid? triGrid; + late GSprite container; @override Future addedToStage() async { - stage.color = Colors.grey.shade800; + stage!.color = Colors.grey.shade800; container = GSprite(); addChild(container); mouseChildren = false; - var texture = await ResourceLoader.loadTexture( - 'assets/trigrid/cute_dog.png', 1, 'dog'); + var texture = await (ResourceLoader.loadTexture( + 'assets/trigrid/cute_dog.png', 1, 'dog') as Future); - cols = texture.width ~/ sep; - rows = texture.height ~/ sep; + cols = texture.width! ~/ sep; + rows = texture.height! ~/ sep; var total = cols * rows; dots = List.generate(total, (index) { var d = GraphPoint(); - var idx = index % cols ?? 0; - var idy = index ~/ cols ?? 0; + var idx = index % cols; + var idy = index ~/ cols; if (index == 0) { d.tx = d.x = 0; d.ty = d.y = 0; @@ -53,21 +53,21 @@ class DrawTriangleGridScene extends GSprite { triGrid = TriangleGrid(res: sep, cols: cols, rows: rows); /// show the triangles lines - triGrid.debugTriangles = true; + triGrid!.debugTriangles = true; - container.addChildAt(triGrid, 0); - triGrid.texture = texture; - triGrid.draw(); + container.addChildAt(triGrid!, 0); + triGrid!.texture = texture; + triGrid!.draw(); } void adjustContainer() { /// resize container based on the image dimensions. - var tw = triGrid.texture.width; - var th = triGrid.texture.height; - var scaleTo = stage.stageHeight / th; + var tw = triGrid!.texture!.width!; + var th = triGrid!.texture!.height!; + var scaleTo = stage!.stageHeight / th; container.y = 0; container.scale = scaleTo; - container.x = (stage.stageWidth - (tw * scaleTo)) / 2; + container.x = (stage!.stageWidth - (tw * scaleTo)) / 2; } @override @@ -80,14 +80,14 @@ class DrawTriangleGridScene extends GSprite { } void renderPoints() { - var ver = triGrid.vertices; + var ver = triGrid!.vertices; var j = 0; for (var i = 0; i < dots.length; ++i) { var d = dots[i]; - ver[j++] = d.x; + ver![j++] = d.x; ver[j++] = d.y; } - triGrid.draw(); + triGrid!.draw(); } void updatePoints() { @@ -97,7 +97,7 @@ class DrawTriangleGridScene extends GSprite { // container.x = (sw - cols * sep) / 2; // container.y = (sh - rows * sep) / 2; - if (stage.pointer.isDown) { + if (stage!.pointer!.isDown) { radius = -targetRadius / 4; } else { radius = targetRadius; diff --git a/example/lib/demos/trigrid/scene/tri_grid.dart b/example/lib/demos/trigrid/scene/tri_grid.dart index 0d10474..b5f2a27 100644 --- a/example/lib/demos/trigrid/scene/tri_grid.dart +++ b/example/lib/demos/trigrid/scene/tri_grid.dart @@ -7,10 +7,10 @@ class TriangleGrid extends GShape { int rows, cols; bool debugTriangles = false; - GTexture texture; + GTexture? texture; TriangleGrid({ - GSprite doc, + GSprite? doc, this.res = 10, this.cols = 5, this.rows = 5, @@ -20,22 +20,22 @@ class TriangleGrid extends GShape { draw(); } - List vertices; - List uvData; - List indices; + List? vertices; + List? uvData; + List? indices; void draw() { graphics.clear(); if (texture != null) { graphics - .beginBitmapFill(texture, null, false, true) - .drawTriangles(vertices, indices, uvData) + .beginBitmapFill(texture!, null, false, true) + .drawTriangles(vertices!, indices, uvData) .endFill(); } if (debugTriangles) { graphics .lineStyle(0, Colors.white30) - .drawTriangles(vertices, indices, uvData) + .drawTriangles(vertices!, indices, uvData) .endFill(); } } @@ -48,18 +48,18 @@ class TriangleGrid extends GShape { for (var c = 0; c < total; ++c) { var i = c ~/ cols; var j = c % cols; - vertices.addAll([j * res, i * res]); - uvData.addAll([ + vertices!.addAll([j * res, i * res]); + uvData!.addAll([ j / (cols - 1), i / (rows - 1), ]); if (i < rows - 1 && j < cols - 1) { ///first tri - indices.addAll([i * cols + j, i * cols + j + 1, (i + 1) * cols + j]); + indices!.addAll([i * cols + j, i * cols + j + 1, (i + 1) * cols + j]); ///first tri - indices.addAll( + indices!.addAll( [i * cols + j + 1, (i + 1) * cols + j + 1, (i + 1) * cols + j]); } } diff --git a/example/lib/demos/universo_flutter_intro/scene.dart b/example/lib/demos/universo_flutter_intro/scene.dart index d1d4f67..2188cf8 100644 --- a/example/lib/demos/universo_flutter_intro/scene.dart +++ b/example/lib/demos/universo_flutter_intro/scene.dart @@ -4,21 +4,21 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; class UniversoFlutterScene extends GSprite { - GSprite logo, fLogo; - GShape planetCirc, ringBack, ringFront; - GShape fLogo1, fLogo2, fLogo3; + late GSprite logo, fLogo; + late GShape planetCirc, ringBack, ringFront; + GShape? fLogo1, fLogo2, fLogo3; @override void addedToStage() { - stage.color = Color(0xff212121); - stage.maskBounds = true; - stage.showBoundsRect = true; + stage!.color = Color(0xff212121); + stage!.maskBounds = true; + stage!.showBoundsRect = true; _buildLogo(); } - double get sw => stage.stageWidth; + double get sw => stage!.stageWidth; - double get sh => stage.stageHeight; + double get sh => stage!.stageHeight; void _buildLogo() { _buildStars(); @@ -52,8 +52,8 @@ class UniversoFlutterScene extends GSprite { fLogo1 = _buildPill(fLogo, 144, fH); fLogo2 = _buildPill(fLogo, 97, fH); fLogo3 = _buildPill(fLogo, 97, fH); - fLogo2.rotation = deg2rad(90); - fLogo2.y = fLogo3.y = 54; + fLogo2!.rotation = deg2rad(90); + fLogo2!.y = fLogo3!.y = 54; fLogo.alignPivot(); fLogo.y -= 54; @@ -137,9 +137,9 @@ class UniversoFlutterScene extends GSprite { fLogo.setProps(rotation: 0); - fLogo1.setProps(scaleX: 0.5, scaleY: .7, alpha: 0, rotation: 1.9); - fLogo2.setProps(scaleX: 0.2, scaleY: .5, alpha: 0, rotation: 0); - fLogo3.setProps(scaleX: 0.6, scaleY: .2, alpha: 0, rotation: rot); + fLogo1!.setProps(scaleX: 0.5, scaleY: .7, alpha: 0, rotation: 1.9); + fLogo2!.setProps(scaleX: 0.2, scaleY: .5, alpha: 0, rotation: 0); + fLogo3!.setProps(scaleX: 0.6, scaleY: .2, alpha: 0, rotation: rot); logo.tween(duration: 1.6, scale: 1, rotation: 0, ease: GEase.easeInOutCirc); planetCirc.tween(duration: 2.5, alpha: 1, ease: GEase.easeInSine); @@ -158,14 +158,14 @@ class UniversoFlutterScene extends GSprite { alpha: 1, ); - fLogo1.tween( + fLogo1!.tween( duration: .4, delay: .4, scale: 1, alpha: 1, overwrite: 0, ); - fLogo1.tween( + fLogo1!.tween( duration: .8, delay: .6, rotation: 0, @@ -173,14 +173,14 @@ class UniversoFlutterScene extends GSprite { overwrite: 0, ); - fLogo2.tween( + fLogo2!.tween( delay: .9, duration: .4, scale: 1, alpha: 1, overwrite: 0, ); - fLogo2.tween( + fLogo2!.tween( delay: .9, duration: .7, rotation: rot, @@ -188,14 +188,14 @@ class UniversoFlutterScene extends GSprite { overwrite: 0, ); - fLogo3.tween( + fLogo3!.tween( delay: 1, duration: .5, scale: 1, alpha: 1, overwrite: 0, ); - fLogo3.tween( + fLogo3!.tween( delay: 1, duration: .7, rotation: 0, diff --git a/example/lib/demos/xmas/xmas.dart b/example/lib/demos/xmas/xmas.dart index 9658465..42edeef 100644 --- a/example/lib/demos/xmas/xmas.dart +++ b/example/lib/demos/xmas/xmas.dart @@ -9,7 +9,7 @@ import 'package:graphx/graphx.dart'; import 'xmas_scene.dart'; class XmasMain extends StatefulWidget { - XmasMain({Key key}) : super(key: key); + XmasMain({Key? key}) : super(key: key); @override _XmasMainState createState() => _XmasMainState(); } @@ -47,7 +47,7 @@ class _XmasMainState extends State { ), Text( '$_counter', - style: Theme.of(context).textTheme.headline4.copyWith( + style: Theme.of(context).textTheme.headline4!.copyWith( shadows: [ Shadow( color: Colors.black.withOpacity(.7), diff --git a/example/lib/demos/xmas/xmas_scene.dart b/example/lib/demos/xmas/xmas_scene.dart index 2b214a0..29f458f 100644 --- a/example/lib/demos/xmas/xmas_scene.dart +++ b/example/lib/demos/xmas/xmas_scene.dart @@ -10,9 +10,9 @@ import 'package:graphx/graphx.dart'; class SnowScene extends GSprite { int numTextureVariants = 6; int numFlakes = 100; - final List _textures = []; - List flakes; - Timer _snowDirectionTimer; + final List _textures = []; + List flakes = []; + late Timer _snowDirectionTimer; @override Future addedToStage() async { @@ -28,8 +28,8 @@ class SnowScene extends GSprite { var flake = Snowflake(texture); addChild(flake); flake.setPosition( - Math.randomRange(0, stage.stageWidth), - Math.randomRange(0, stage.stageHeight), + Math.randomRange(0, stage!.stageWidth), + Math.randomRange(0, stage!.stageHeight), ); return flake; }); @@ -59,12 +59,12 @@ class SnowScene extends GSprite { flake.y += flake.velY; /// check the stage bounds (Scaffold::body) - if (flake.y > stage.stageHeight) { + if (flake.y > stage!.stageHeight) { flake.y = -flake.height; } if (flake.x < -flake.width) { - flake.x = stage.stageWidth; - } else if (flake.x > stage.stageWidth) { + flake.x = stage!.stageWidth; + } else if (flake.x > stage!.stageWidth) { flake.x = -flake.width; } }); @@ -89,10 +89,10 @@ class Snowflake extends GBitmap { minVelY = .5, maxVelY = 2.5; - double velY, velX; + double velY = 0.0, velX = 0.0; /// GBitmap requires the Texture in the constructor. - Snowflake(GTexture texture) : super(texture) { + Snowflake(GTexture? texture) : super(texture) { _init(); } diff --git a/example/lib/main.dart b/example/lib/main.dart index 6bdee0c..906222a 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -36,7 +36,10 @@ void main() { // home: SimpleRadialMenuMain(), // home: MuratCoffeeMain(), // home: PieChartMain(), + + //TODO doesn't work // home: ChartBezierMain(), + // home: RunHeroCanvasMain(), // home: ElasticBandMain(), // home: FlowerGradientMain(), @@ -47,14 +50,20 @@ void main() { // home: PizzaBoxMain(), // home: DrawingPadBezierMain(), // home: IsmaChartMain(), + + //TODO doesn't work // home: TriGridMain(), + // home: NicoLoadingIndicatorMain(), // home: FeelingSwitchMain(), // home: MouseRepulsionMain(), // home: Globe3dMain(), // home: LungsAnimationMain(), // home: PathChartStressTestMain(), + + //TODO doesn't work // home: ExpanderFabMenu(), + home: PageIndicatorMain(), ), ); diff --git a/example/lib/utils/base_scene.dart b/example/lib/utils/base_scene.dart index 88f09ce..af361cd 100644 --- a/example/lib/utils/base_scene.dart +++ b/example/lib/utils/base_scene.dart @@ -4,7 +4,7 @@ class BaseScene extends GSprite { double get sw => stage?.stageWidth ?? 0; double get sh => stage?.stageHeight ?? 0; - BaseScene([GSprite doc]) { + BaseScene([GSprite? doc]) { doc?.addChild(this); } } diff --git a/example/lib/utils/demo_scene_widget.dart b/example/lib/utils/demo_scene_widget.dart index 860001b..9e3d71b 100644 --- a/example/lib/utils/demo_scene_widget.dart +++ b/example/lib/utils/demo_scene_widget.dart @@ -4,13 +4,13 @@ import 'package:graphx/graphx.dart'; class DemoSingleSceneWidget extends StatelessWidget { final GSprite root; final String title; - final Widget child; - final SceneConfig config; + final Widget? child; + final SceneConfig? config; const DemoSingleSceneWidget({ - Key key, - @required this.root, - @required this.title, + Key? key, + required this.root, + required this.title, this.config, this.child, }) : super(key: key); @@ -19,7 +19,7 @@ class DemoSingleSceneWidget extends StatelessWidget { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text(title ?? 'GraphX demo'), + title: Text(title), ), /// takes the entire body area. diff --git a/example/lib/utils/svg_utils.dart b/example/lib/utils/svg_utils.dart index d9f75ae..57f0c9a 100644 --- a/example/lib/utils/svg_utils.dart +++ b/example/lib/utils/svg_utils.dart @@ -1,48 +1,48 @@ -import 'dart:ui' as ui; +// import 'dart:ui' as ui; -import 'package:flutter_svg/flutter_svg.dart' as svg; -import 'package:graphx/graphx.dart'; +// import 'package:flutter_svg/flutter_svg.dart' as svg; +// import 'package:graphx/graphx.dart'; -/// Utilities to work with `flutter_svg`. -class SvgUtils { - static Future svgStringToSvgDrawable(String rawSvg) async { - return await svg.svg.fromSvgString(rawSvg, rawSvg); - } +// /// Utilities to work with `flutter_svg`. +// class SvgUtils { +// static Future svgStringToSvgDrawable(String rawSvg) async { +// return await svg.svg.fromSvgString(rawSvg, rawSvg); +// } - static Future svgStringToPicture(String rawSvg) async { - final svgRoot = await svg.svg.fromSvgString(rawSvg, rawSvg); - return svgRoot.toPicture(); - } +// static Future svgStringToPicture(String rawSvg) async { +// final svgRoot = await svg.svg.fromSvgString(rawSvg, rawSvg); +// return svgRoot.toPicture(); +// } - static void svgStringToCanvas( - String rawSvg, - ui.Canvas canvas, { - bool scaleCanvas = true, - bool clipCanvas = true, - ui.Size scaleCanvasSize, - }) async { - final svgRoot = await svg.svg.fromSvgString(rawSvg, rawSvg); - if (scaleCanvas) { - svgRoot.scaleCanvasToViewBox(canvas, scaleCanvasSize); - } - if (clipCanvas) { - svgRoot.clipCanvasToViewBox(canvas); - } - svgRoot.draw(canvas, null); - } +// static void svgStringToCanvas( +// String rawSvg, +// ui.Canvas canvas, { +// bool scaleCanvas = true, +// bool clipCanvas = true, +// ui.Size? scaleCanvasSize, +// }) async { +// final svgRoot = await svg.svg.fromSvgString(rawSvg, rawSvg); +// if (scaleCanvas) { +// svgRoot.scaleCanvasToViewBox(canvas, scaleCanvasSize!); +// } +// if (clipCanvas) { +// svgRoot.clipCanvasToViewBox(canvas); +// } +// svgRoot.draw(canvas, null); +// } - static Future svgDataFromString(String rawSvg) async { - final svgRoot = await svg.svg.fromSvgString(rawSvg, rawSvg); - var obj = SvgData(); - obj.hasContent = svgRoot.hasDrawableContent; - obj.picture = svgRoot.toPicture(); - obj.viewBox = GRect.fromNative(svgRoot.viewport.viewBoxRect); - obj.size = GRect( - 0, - 0, - svgRoot.viewport.size.width, - svgRoot.viewport.size.height, - ); - return obj; - } -} +// static Future svgDataFromString(String rawSvg) async { +// final svgRoot = await svg.svg.fromSvgString(rawSvg, rawSvg); +// var obj = SvgData(); +// obj.hasContent = svgRoot.hasDrawableContent; +// obj.picture = svgRoot.toPicture(); +// obj.viewBox = GRect.fromNative(svgRoot.viewport.viewBoxRect); +// obj.size = GRect( +// 0, +// 0, +// svgRoot.viewport.size.width, +// svgRoot.viewport.size.height, +// ); +// return obj; +// } +// } diff --git a/example/pubspec.yaml b/example/pubspec.yaml index 0ffa6c9..b75cf6d 100644 --- a/example/pubspec.yaml +++ b/example/pubspec.yaml @@ -6,12 +6,11 @@ publish_to: "none" version: 1.0.0+22 environment: - sdk: ">=2.7.0 <3.0.0" + sdk: '>=2.12.0 <3.0.0' dependencies: flutter: sdk: flutter - flutter_icons: ^1.1.0 flutter_svg: ^0.21.0-nullsafety.0 graphx: path: ../ diff --git a/lib/src/render/graphics.dart b/lib/src/render/graphics.dart index 1d3a5d6..7e1478d 100644 --- a/lib/src/render/graphics.dart +++ b/lib/src/render/graphics.dart @@ -588,14 +588,14 @@ class Graphics with RenderUtilMixin implements GxRenderable { int sides, [ double rotation = 0, ]) { - final points = List.filled(sides, Offset(0, 0)); + final points = List.filled(sides, Offset(0, 0)); final rel = 2 * Math.PI / sides; for (var i = 1; i <= sides; ++i) { final px = x + radius * Math.cos(i * rel + rotation); final py = y + radius * Math.sin(i * rel + rotation); points[i - 1] = Offset(px, py); } - _path!.addPolygon(points as List, true); + _path!.addPolygon(points, true); return this; } @@ -743,7 +743,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { } else { canvas!.drawVertices( graph.vertices!.rawData!, - graph.vertices!.blendMode, + graph.vertices!.blendMode!, fill, ); } @@ -834,7 +834,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { List? indices, List? uvtData, List? hexColors, - BlendMode blendMode = BlendMode.src, + BlendMode? blendMode = BlendMode.src, Culling culling = Culling.positive, ]) { /// will only work if it has a fill. @@ -922,8 +922,8 @@ extension ExtSkiaPaintCustom on Paint { class _GraphVertices { List? vertices, uvtData, adjustedUvtData; List? colors, indices; - BlendMode blendMode; - VertexMode mode; + BlendMode? blendMode; + VertexMode? mode; Path? _path; Rect? _bounds; late bool _normalizedUvt; diff --git a/lib/src/tween/src/wraps/common_wraps.dart b/lib/src/tween/src/wraps/common_wraps.dart index cd993b6..c16b212 100644 --- a/lib/src/tween/src/wraps/common_wraps.dart +++ b/lib/src/tween/src/wraps/common_wraps.dart @@ -29,7 +29,7 @@ class GTweenableDouble with GTweenable, SingleValueTweenMixin { static GTweenable? wrap(Object? target) => target is double ? GTweenableDouble(target) : null; - double? value; + double value = 0.0; GTweenableDouble(double target) { value = this.target = target; diff --git a/lib/src/utils/svg_utils.dart b/lib/src/utils/svg_utils.dart index b0f6ab6..af191a6 100644 --- a/lib/src/utils/svg_utils.dart +++ b/lib/src/utils/svg_utils.dart @@ -1,48 +1,49 @@ -// import 'package:flutter_svg/flutter_svg.dart' as svg; -// -// import '../../graphx.dart'; -// -// /// Utilities to work with `flutter_svg`. -// class SvgUtils { -// static Future -// svgStringToSvgDrawable(String rawSvg) async { -// return await svg.svg.fromSvgString(rawSvg, rawSvg); -// } -// -// static Future svgStringToPicture(String rawSvg) async { -// final svgRoot = await svg.svg.fromSvgString(rawSvg, rawSvg); -// return svgRoot.toPicture(); -// } -// -// static void svgStringToCanvas( -// String rawSvg, -// Canvas canvas, { -// bool scaleCanvas = true, -// bool clipCanvas = true, -// Size scaleCanvasSize, -// }) async { -// final svgRoot = await svg.svg.fromSvgString(rawSvg, rawSvg); -// if (scaleCanvas) { -// svgRoot.scaleCanvasToViewBox(canvas, scaleCanvasSize); -// } -// if (clipCanvas) { -// svgRoot.clipCanvasToViewBox(canvas); -// } -// svgRoot.draw(canvas, null); -// } -// -// static Future svgDataFromString(String rawSvg) async { -// final svgRoot = await svg.svg.fromSvgString(rawSvg, rawSvg); -// var obj = SvgData(); -// obj.hasContent = svgRoot.hasDrawableContent; -// obj.picture = svgRoot.toPicture(); -// obj.viewBox = GxRect.fromNative(svgRoot.viewport.viewBoxRect); -// obj.size = GxRect( -// 0, -// 0, -// svgRoot.viewport.size.width, -// svgRoot.viewport.size.height, -// ); -// return obj; -// } -// } +import 'dart:ui'; + +import 'package:flutter_svg/flutter_svg.dart' as svg; + +import '../../graphx.dart'; + +/// Utilities to work with `flutter_svg`. +class SvgUtils { + static Future svgStringToSvgDrawable(String rawSvg) async { + return await svg.svg.fromSvgString(rawSvg, rawSvg); + } + + static Future svgStringToPicture(String rawSvg) async { + final svgRoot = await svg.svg.fromSvgString(rawSvg, rawSvg); + return svgRoot.toPicture(); + } + + static void svgStringToCanvas( + String rawSvg, + Canvas canvas, { + bool scaleCanvas = true, + bool clipCanvas = true, + required Size scaleCanvasSize, + }) async { + final svgRoot = await svg.svg.fromSvgString(rawSvg, rawSvg); + if (scaleCanvas) { + svgRoot.scaleCanvasToViewBox(canvas, scaleCanvasSize); + } + if (clipCanvas) { + svgRoot.clipCanvasToViewBox(canvas); + } + svgRoot.draw(canvas, Rect.zero); + } + + static Future svgDataFromString(String rawSvg) async { + final svgRoot = await svg.svg.fromSvgString(rawSvg, rawSvg); + var obj = SvgData(); + obj.hasContent = svgRoot.hasDrawableContent; + obj.picture = svgRoot.toPicture(); + obj.viewBox = GRect.fromNative(svgRoot.viewport.viewBoxRect); + obj.size = GRect( + 0, + 0, + svgRoot.viewport.size.width, + svgRoot.viewport.size.height, + ); + return obj; + } +} diff --git a/pubspec.lock b/pubspec.lock index 9d3f47d..7efaa62 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -55,6 +55,13 @@ packages: description: flutter source: sdk version: "0.0.0" + flutter_svg: + dependency: "direct main" + description: + name: flutter_svg + url: "https://pub.dartlang.org" + source: hosted + version: "0.21.0-nullsafety.0" flutter_test: dependency: "direct dev" description: flutter @@ -95,6 +102,20 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "1.8.0" + path_drawing: + dependency: transitive + description: + name: path_drawing + url: "https://pub.dartlang.org" + source: hosted + version: "0.5.0-nullsafety.0" + path_parsing: + dependency: transitive + description: + name: path_parsing + url: "https://pub.dartlang.org" + source: hosted + version: "0.2.0-nullsafety.0" pedantic: dependency: transitive description: @@ -179,3 +200,4 @@ packages: version: "5.0.2" sdks: dart: ">=2.12.0 <3.0.0" + flutter: ">=1.24.0-7.0" diff --git a/pubspec.yaml b/pubspec.yaml index f0c8587..5b7ff0a 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -4,14 +4,14 @@ version: 0.9.9 homepage: https://github.com/roipeker/graphx environment: - sdk: '>=2.12.0 <3.0.0' + sdk: ">=2.12.0 <3.0.0" dependencies: flutter: sdk: flutter xml: ^5.0.0-nullsafety.1 http: ^0.13.0-nullsafety.0 -# flutter_svg: 0.19.0 + flutter_svg: ^0.21.0-nullsafety.0 dev_dependencies: flutter_test: From bc12fda7c6e973d57a2e437a2f1b501db944c523 Mon Sep 17 00:00:00 2001 From: Roi Peker Date: Thu, 25 Mar 2021 20:42:55 -0300 Subject: [PATCH 2/2] critical fixes for null-safety. -several core fixes for null-safety. -fixed the non-working examples. -added some comments in the README. -increased the version. --- CHANGELOG.md | 5 + README.md | 11 +- .../lib/demos/chart_bezier/bezier_points.dart | 36 +- .../chart_bezier/curved_graph_scene.dart | 42 +- .../expander_fab_menu/expander_fab_menu.dart | 70 +--- example/lib/demos/mouse_repulsion/scene.dart | 2 +- .../simple_interactions/ui/my_button.dart | 4 +- example/lib/demos/trigrid/scene/scene.dart | 46 ++- example/lib/demos/trigrid/scene/tri_grid.dart | 26 +- example/lib/main.dart | 7 - example/pubspec.yaml | 2 +- example/readme.md | 16 + lib/src/core/scene_config.dart | 25 +- lib/src/core/scene_controller.dart | 57 +-- lib/src/core/scene_painter.dart | 8 +- lib/src/display/stage.dart | 4 +- lib/src/display/text.dart | 2 +- lib/src/input/input_converter.dart | 24 +- lib/src/log/trace.dart | 20 +- lib/src/render/graphics.dart | 365 +++++++++--------- lib/src/tween/src/gtween.dart | 90 +++-- lib/src/tween/src/mixins/tweenable.dart | 24 +- lib/src/tween/src/wraps/common_wraps.dart | 6 +- lib/src/widgets/graphx_widget.dart | 25 +- pubspec.lock | 2 +- pubspec.yaml | 6 +- 26 files changed, 461 insertions(+), 464 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 82b79ae..ac4744f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,8 @@ +## [1.0.0-nullsafety.0] +- initial migration to null-safety +- fix non-working examples. +- fix a bug with GText layout. + ## [0.9.9] - major fix for `GTween` when running lots of SceneControllers instances. - fix stage dispose exception with keyboard/pointer. diff --git a/README.md b/README.md index 49899f1..db81ac5 100644 --- a/README.md +++ b/README.md @@ -20,12 +20,21 @@ To get some extended, boring explanations, and eventually some sample codes, che --- -[Try Graphx on Dart Pad](https://dartpad.dev/21b6670a42d32e37440192e19279e71b?) +[Try Graphx (0.0.9) on Dart Pad](https://dartpad.dev/21b6670a42d32e37440192e19279e71b?) + +#### news! + +- WIP Support for [null-safety](https://github.com/roipeker/graphx/tree/null-safety) + +- Support for HotReload #### prototyping GraphX is all about visuals, here you have some screen captures of random prototypes I've been doing, while developing and testing graphx. +For your GraphX scene to support **Hot Reload**, you should initialize your variables and DisplayObjects inside `addedToStage`, and optionally clean them in `dispose`. + + [![artificial horizon](https://media.giphy.com/media/NMG8gfpJxFiu1eALZo/giphy.gif)](https://media.giphy.com/media/NMG8gfpJxFiu1eALZo/source.mp4) [![parallax game](https://media.giphy.com/media/RIrvhfZoDtal41Tb4e/giphy-downsized.gif)](https://media.giphy.com/media/RIrvhfZoDtal41Tb4e/source.mp4) [![charts pie color 2](https://media.giphy.com/media/pQdeurUOAqWdZuxxUK/giphy.gif)](https://media.giphy.com/media/pQdeurUOAqWdZuxxUK/source.mp4) diff --git a/example/lib/demos/chart_bezier/bezier_points.dart b/example/lib/demos/chart_bezier/bezier_points.dart index 8092542..936856c 100644 --- a/example/lib/demos/chart_bezier/bezier_points.dart +++ b/example/lib/demos/chart_bezier/bezier_points.dart @@ -1,12 +1,10 @@ import 'package:graphx/graphx.dart'; class _BezierControlPoint { - GPoint? prev; - GPoint? next; - - _BezierControlPoint([this.prev, this.next]) { - prev ??= GPoint(); - next ??= GPoint(); + late GPoint prev, next; + _BezierControlPoint() { + prev = GPoint(); + next = GPoint(); } } @@ -16,7 +14,7 @@ void bezierCurveThrough( Graphics g, List points, [ double tension = .25, - List? output, + List? output, ]) { var len = points.length; if (len == 2) { @@ -49,19 +47,19 @@ void bezierCurveThrough( var cnx = pi.x + dx * dn * tension; var cny = pi.y + dy * dn * tension; - cpoints[i].prev!.setTo(cpx, cpy); - cpoints[i].next!.setTo(cnx, cny); + cpoints[i].prev.setTo(cpx, cpy); + cpoints[i].next.setTo(cnx, cny); } /// end points cpoints[0].next = GPoint( - (points[0].x + cpoints[1].prev!.x) / 2, - (points[0].y + cpoints[1].prev!.y) / 2, + (points[0].x + cpoints[1].prev.x) / 2, + (points[0].y + cpoints[1].prev.y) / 2, ); cpoints[len - 1].prev = GPoint( - (points[len - 1].x + cpoints[len - 2].next!.x) / 2, - (points[len - 1].y + cpoints[len - 2].next!.y) / 2, + (points[len - 1].x + cpoints[len - 2].next.x) / 2, + (points[len - 1].y + cpoints[len - 2].next.y) / 2, ); /// draw? @@ -71,19 +69,19 @@ void bezierCurveThrough( var p = points[i]; var cp = cpoints[i]; var cpp = cpoints[i - 1]; - g.cubicCurveTo(cpp.next!.x, cpp.next!.y, cp.prev!.x, cp.prev!.y, p.x, p.y); + g.cubicCurveTo(cpp.next.x, cpp.next.y, cp.prev.x, cp.prev.y, p.x, p.y); output?.addAll([cpp.next, cp.prev, p]); } cpoints.clear(); } -void bezierCurveThroughDraw(Graphics g, List points) { - g.moveTo(points[0]!.x, points[0]!.y); +void bezierCurveThroughDraw(Graphics g, List points) { + g.moveTo(points[0].x, points[0].y); final len = points.length; for (var i = 1; i < len; i += 3) { - final p0 = points[i]!; - final p1 = points[i + 1]!; - final p2 = points[i + 2]!; + final p0 = points[i]; + final p1 = points[i + 1]; + final p2 = points[i + 2]; g.cubicCurveTo(p0.x, p0.y, p1.x, p1.y, p2.x, p2.y); } } diff --git a/example/lib/demos/chart_bezier/curved_graph_scene.dart b/example/lib/demos/chart_bezier/curved_graph_scene.dart index 6164415..0adb454 100644 --- a/example/lib/demos/chart_bezier/curved_graph_scene.dart +++ b/example/lib/demos/chart_bezier/curved_graph_scene.dart @@ -5,9 +5,10 @@ import 'bezier_points.dart'; class CurvedGraphScene extends GSprite { List graphPositions = [.2, .4, .9, .3, .6, .7, .9, .3]; - List? bezierPoints; + List bezierPoints = []; double get graphW => stage!.stageWidth; + double get graphH => stage!.stageHeight; late GSprite graph, dots; @@ -17,25 +18,13 @@ class CurvedGraphScene extends GSprite { late GTweenableList myTweenList; late List lastPercents; - GShape drawCircle(double px, double py) { - var sh = GShape(); - dots.addChild(sh); - sh.graphics.beginFill(Colors.red).drawCircle(0, 0, 2).endFill(); - sh.setPosition(px, py); - return sh; - } - @override void addedToStage() { - bezierPoints = []; - // stage.color = Colors.black; stage!.maskBounds = true; - graph = GSprite(); dots = GSprite(); lines = GShape(); filled = GShape(); - addChild(filled); addChild(lines); addChild(graph); @@ -58,7 +47,6 @@ class CurvedGraphScene extends GSprite { } void randomNumbers() { - var newValues = lastPercents.map((e) => Math.random()).toList(); for (var i = 0; i < dots.children.length; ++i) { var dot = dots.children[i]; dot.tween( @@ -80,24 +68,26 @@ class CurvedGraphScene extends GSprite { colorize: Colors.red, ); } + final newValues = lastPercents.map((e) => Math.random()).toList(); myTweenList.tween( newValues, duration: 2, onUpdate: () { - final values = myTweenList.value as List; + final values = myTweenList.value as List; renderPositions(values); }, ease: GEase.fastLinearToSlowEaseIn, ); } - void renderPositions(List percents) { + void renderPositions(List percents) { for (var i = 0; i < percents.length; ++i) { - coords[i].y = percents[i]! * graphH; - dots.getChildAt(i).y = coords[i].y; + coords[i].y = percents[i] * graphH; + final dot = dots.getChildAt(i); + dot.y = coords[i].y; } lines.graphics.clear(); - lines.graphics.lineStyle(1, Colors.black); + lines.graphics.lineStyle(1, Colors.blue); lines.graphics.lineGradientStyle( GradientType.linear, [ @@ -106,7 +96,7 @@ class CurvedGraphScene extends GSprite { ], ratios: [.1, 1], ); - bezierPoints!.clear(); + bezierPoints.clear(); bezierCurveThrough(lines.graphics, coords, .25, bezierPoints); filled.graphics.clear(); @@ -120,11 +110,19 @@ class CurvedGraphScene extends GSprite { begin: Alignment.topCenter, end: Alignment.bottomCenter, ); - bezierCurveThroughDraw(filled.graphics, bezierPoints!); + bezierCurveThroughDraw(filled.graphics, bezierPoints); filled.graphics .lineTo(graphW, graphH) .lineTo(0, graphH) - .lineTo(bezierPoints![0]!.x, bezierPoints![0]!.y) + .lineTo(bezierPoints[0].x, bezierPoints[0].y) .endFill(); } + + GShape drawCircle(double px, double py) { + var sh = GShape(); + dots.addChild(sh); + sh.graphics.beginFill(Colors.red).drawCircle(0, 0, 2).endFill(); + sh.setPosition(px, py); + return sh; + } } diff --git a/example/lib/demos/expander_fab_menu/expander_fab_menu.dart b/example/lib/demos/expander_fab_menu/expander_fab_menu.dart index fe5d8b3..233af38 100644 --- a/example/lib/demos/expander_fab_menu/expander_fab_menu.dart +++ b/example/lib/demos/expander_fab_menu/expander_fab_menu.dart @@ -62,13 +62,7 @@ class _MyMenuState extends State with TickerProviderStateMixin { @override void initState() { super.initState(); - // anim = AnimationController( - // vsync: this, - // duration: dur, - // ); - // anim.addListener(() { - // setState(() {}); - // }); + menuScene.requestPositionCallback = getPosition; WidgetsBinding.instance!.addPostFrameCallback((timeStamp) { getPosition(); }); @@ -116,10 +110,6 @@ class _MyMenuState extends State with TickerProviderStateMixin { color: Colors.transparent, key: mySuperKey, ), - // Visibility( - // visible: !isOpen, - // child: myFav(), - // ), baseButton, baseButton, ], @@ -134,54 +124,29 @@ class _MyMenuState extends State with TickerProviderStateMixin { ), ); } - -// Widget buildAnimFab() { -// print(isOpen); -// print(anim.value); -// print(pos); -// if (!isOpen) {} -// return Positioned( -// top: pos.dy * (1 - anim.value), -// left: pos.dx, -// child: IconButton( -// // key: mySuperKey, -// icon: Icon( -// Icons.accessibility, -// color: Colors.red, -// ), -// // backgroundColor: Colors.white, -// onPressed: () { -// isOpen = !isOpen; -// trace('pressed', isOpen); -// if (isOpen) { -// anim.forward(); -// } else { -// anim.reverse(); -// } -// }, -// ), -// ); -// } } class MyCoolMenuScene extends GSprite { - late MyButton button; - bool isOpen = false; + late VoidCallback requestPositionCallback; + late MyButton button; + double? buttonY; + late GShape curtain; + late GSprite menuContainer; MyCoolMenuScene() { button = MyButton(); } - double? buttonY; - late GShape curtain; void updatePosition(GRect position) { button.x = position.x + position.width / 2; - button.y = buttonY = position.y + position.height / 2; + buttonY = position.y + position.height / 2; + if( !isOpen ){ + button.y = buttonY; + } } - GSprite? menuContainer; @override void addedToStage() { @@ -190,10 +155,18 @@ class MyCoolMenuScene extends GSprite { addChild(curtain); menuContainer = GSprite(); - addChild(menuContainer!); + addChild(menuContainer); _buildMenu(); addChild(button); + stage!.onResized.add((){ + requestPositionCallback.call(); + menuContainer.setPosition(sw / 2, sh / 2); + if( isOpen ){ + _renderCurt(); + } + }); + button.onMouseClick.add((event) { isOpen = !isOpen; button.open(isOpen); @@ -262,7 +235,6 @@ class MyCoolMenuScene extends GSprite { void _renderCurt() { final g = curtain.graphics; - g.clear(); // g.lineStyle(2, Colors.black); g.beginFill(Colors.red); @@ -289,8 +261,8 @@ class MyCoolMenuScene extends GSprite { itm.y = i * 34.0; items.add(itm); } - menuContainer!.alignPivot(); - menuContainer!.setPosition(sw / 2, sh / 2); + menuContainer.alignPivot(); + menuContainer.setPosition(sw / 2, sh / 2); } void showMenuNow() { diff --git a/example/lib/demos/mouse_repulsion/scene.dart b/example/lib/demos/mouse_repulsion/scene.dart index fd0b5c1..78d0c7c 100644 --- a/example/lib/demos/mouse_repulsion/scene.dart +++ b/example/lib/demos/mouse_repulsion/scene.dart @@ -22,7 +22,7 @@ class MouseRepulsionScene extends GSprite { mouseChildren = false; mouseRadiusShape = GShape(); radiusSq = radius * radius; - sep = 6; + sep = 12; cols = 70; rows = 60; diff --git a/example/lib/demos/simple_interactions/ui/my_button.dart b/example/lib/demos/simple_interactions/ui/my_button.dart index 041e2c0..e03dc6e 100644 --- a/example/lib/demos/simple_interactions/ui/my_button.dart +++ b/example/lib/demos/simple_interactions/ui/my_button.dart @@ -153,10 +153,10 @@ class MyButton extends GSprite { /// update the [icon.data] and icon's color, based on [_isOn] current state. void _updateIcon() { if (_isOn) { - icon.data = Icons.brightness_7_outlined; + icon.data = Icons.wb_incandescent; icon.color = Colors.yellow; } else { - icon.data = Icons.brightness_2_outlined; + icon.data = Icons.wb_incandescent_outlined; icon.color = Colors.white; } } diff --git a/example/lib/demos/trigrid/scene/scene.dart b/example/lib/demos/trigrid/scene/scene.dart index e8f3741..e151d34 100644 --- a/example/lib/demos/trigrid/scene/scene.dart +++ b/example/lib/demos/trigrid/scene/scene.dart @@ -5,7 +5,7 @@ import 'point.dart'; import 'tri_grid.dart'; class DrawTriangleGridScene extends GSprite { - static const int res = 6; + static const int res = 3; static const double targetRadius = 120; /// draw triangle parameters. @@ -19,8 +19,10 @@ class DrawTriangleGridScene extends GSprite { late double radiusSq; late List dots; - TriangleGrid? triGrid; + late TriangleGrid triGrid; late GSprite container; + bool inited = false; + double textureW = 0, textureH = 0; @override Future addedToStage() async { @@ -29,15 +31,22 @@ class DrawTriangleGridScene extends GSprite { container = GSprite(); addChild(container); mouseChildren = false; - var texture = await (ResourceLoader.loadTexture( - 'assets/trigrid/cute_dog.png', 1, 'dog') as Future); - - cols = texture.width! ~/ sep; - rows = texture.height! ~/ sep; + final texture = await ResourceLoader.loadTexture( + 'assets/trigrid/cute_dog.png', 1, 'dog'); + if (texture == null) { + throw "We have an error loading the image"; + } + textureW = texture.width!; + textureH = texture.height!; + cols = textureW ~/ sep; + rows = textureH ~/ sep; var total = cols * rows; + /// these are the points that we MOVE to update the grid. dots = List.generate(total, (index) { var d = GraphPoint(); + /// uncomment this to see the DOTS. + // container.addChild(d); var idx = index % cols; var idy = index ~/ cols; if (index == 0) { @@ -53,17 +62,17 @@ class DrawTriangleGridScene extends GSprite { triGrid = TriangleGrid(res: sep, cols: cols, rows: rows); /// show the triangles lines - triGrid!.debugTriangles = true; - - container.addChildAt(triGrid!, 0); - triGrid!.texture = texture; - triGrid!.draw(); + // triGrid.debugTriangles = true; + container.addChildAt(triGrid, 0); + triGrid.texture = texture; + triGrid.draw(); + inited = true; } void adjustContainer() { /// resize container based on the image dimensions. - var tw = triGrid!.texture!.width!; - var th = triGrid!.texture!.height!; + var tw = textureW; + var th = textureH; var scaleTo = stage!.stageHeight / th; container.y = 0; container.scale = scaleTo; @@ -73,21 +82,22 @@ class DrawTriangleGridScene extends GSprite { @override void update(double delta) { super.update(delta); - if (triGrid == null) return; + if (!inited) return; + // return; adjustContainer(); updatePoints(); renderPoints(); } void renderPoints() { - var ver = triGrid!.vertices; + var ver = triGrid.vertices; var j = 0; for (var i = 0; i < dots.length; ++i) { var d = dots[i]; - ver![j++] = d.x; + ver[j++] = d.x; ver[j++] = d.y; } - triGrid!.draw(); + triGrid.draw(); } void updatePoints() { diff --git a/example/lib/demos/trigrid/scene/tri_grid.dart b/example/lib/demos/trigrid/scene/tri_grid.dart index b5f2a27..8a3f01a 100644 --- a/example/lib/demos/trigrid/scene/tri_grid.dart +++ b/example/lib/demos/trigrid/scene/tri_grid.dart @@ -1,4 +1,3 @@ - import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; @@ -7,6 +6,10 @@ class TriangleGrid extends GShape { int rows, cols; bool debugTriangles = false; + late List vertices; + late List uvData; + late List indices; + GTexture? texture; TriangleGrid({ @@ -20,22 +23,18 @@ class TriangleGrid extends GShape { draw(); } - List? vertices; - List? uvData; - List? indices; - void draw() { graphics.clear(); if (texture != null) { graphics .beginBitmapFill(texture!, null, false, true) - .drawTriangles(vertices!, indices, uvData) + .drawTriangles(vertices, indices, uvData) .endFill(); } if (debugTriangles) { graphics .lineStyle(0, Colors.white30) - .drawTriangles(vertices!, indices, uvData) + .drawTriangles(vertices, indices, uvData) .endFill(); } } @@ -48,18 +47,17 @@ class TriangleGrid extends GShape { for (var c = 0; c < total; ++c) { var i = c ~/ cols; var j = c % cols; - vertices!.addAll([j * res, i * res]); - uvData!.addAll([ + vertices.addAll([j * res, i * res]); + uvData.addAll([ j / (cols - 1), i / (rows - 1), ]); - if (i < rows - 1 && j < cols - 1) { - ///first tri - indices!.addAll([i * cols + j, i * cols + j + 1, (i + 1) * cols + j]); + ///first triangle + indices.addAll([i * cols + j, i * cols + j + 1, (i + 1) * cols + j]); - ///first tri - indices!.addAll( + ///second triangle + indices.addAll( [i * cols + j + 1, (i + 1) * cols + j + 1, (i + 1) * cols + j]); } } diff --git a/example/lib/main.dart b/example/lib/main.dart index 906222a..8a62164 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -37,7 +37,6 @@ void main() { // home: MuratCoffeeMain(), // home: PieChartMain(), - //TODO doesn't work // home: ChartBezierMain(), // home: RunHeroCanvasMain(), @@ -50,20 +49,14 @@ void main() { // home: PizzaBoxMain(), // home: DrawingPadBezierMain(), // home: IsmaChartMain(), - - //TODO doesn't work // home: TriGridMain(), - // home: NicoLoadingIndicatorMain(), // home: FeelingSwitchMain(), // home: MouseRepulsionMain(), // home: Globe3dMain(), // home: LungsAnimationMain(), // home: PathChartStressTestMain(), - - //TODO doesn't work // home: ExpanderFabMenu(), - home: PageIndicatorMain(), ), ); diff --git a/example/pubspec.yaml b/example/pubspec.yaml index b75cf6d..e5bce67 100644 --- a/example/pubspec.yaml +++ b/example/pubspec.yaml @@ -3,7 +3,7 @@ description: Graphx rendering prototype examples publish_to: "none" -version: 1.0.0+22 +version: 1.0.0+23 environment: sdk: '>=2.12.0 <3.0.0' diff --git a/example/readme.md b/example/readme.md index e69de29..d4da51f 100644 --- a/example/readme.md +++ b/example/readme.md @@ -0,0 +1,16 @@ +Here you will find an exhaustive list of experiments made with GraphX. + +Some are more complicated than others, but overall is a good resource to learn the "real world" API that GraphX provides. + +Be WARNED: the examples are (mostly) pretty raw, a direct copy of codes I did during the last couple of months as +quick prototypes for experiments while sketching the package. + +Remember, GraphX should be considered WIP. As stated in the root README file, I mostly used it to play, prototype +and have fun creating random stuffs, and that's the spirit of it :) + +Although you are free to use it in production apps (some users are, myself as well), beware that you might find +some bugs, even more in this null-safety branch. + +I truly hope you enjoy using the package, as I much as I do. + +Sincerely, roipeker. \ No newline at end of file diff --git a/lib/src/core/scene_config.dart b/lib/src/core/scene_config.dart index fa4f497..9f474d8 100644 --- a/lib/src/core/scene_config.dart +++ b/lib/src/core/scene_config.dart @@ -51,17 +51,17 @@ class SceneConfig { /// re-builds the SceneController (the ScenePainter and the scene class). /// disposes and initializes all the scene. - bool? rebuildOnHotReload; + late bool rebuildOnHotReload; /// If the GraphX [SceneController] will use keyboard events. - bool? useKeyboard; + late bool useKeyboard; /// If this GraphX [SceneController] will use pointer (touch/mouse) events. - bool? usePointer; + late bool usePointer; /// Will be overwritten to `true` if [autoUpdateAndRender] is set on any /// [ScenePainter] layer. - bool? useTicker; + bool useTicker = false; /// See [CustomPaint.willChange]. /// Rendering caching flag. @@ -71,7 +71,7 @@ class SceneConfig { /// All these flags overrides the value to `true`: /// [autoUpdateRender], [useTicker], [usePointer], [useKeyboard] /// - bool? painterWillChange; + late bool painterWillChange; /// Avoids the scene from being disposed by the Widget. /// Meant to be used with `ScenePainter.useOwnCanvas=true` @@ -79,7 +79,7 @@ class SceneConfig { /// Picture (or Image eventually) by other [ScenePainter]s. /// Warning: Experimental /// - bool? isPersistent = false; + late bool isPersistent; /// Default flag to make the engine update() the Stage and all /// his children (onEnterFrame), needed by [GTween] to run the tweens. @@ -91,7 +91,7 @@ class SceneConfig { /// And, unless you don't need external control over the rendering & update /// pipelines for the scene, or if you use a static scene, /// you should leave it as `true`. - bool? autoUpdateRender = true; + late bool autoUpdateRender; SceneConfig({ this.rebuildOnHotReload = true, @@ -100,21 +100,18 @@ class SceneConfig { this.useTicker = false, this.isPersistent = false, this.autoUpdateRender = true, - this.painterWillChange, + this.painterWillChange = true, }) { - if (autoUpdateRender ?? false) useTicker = true; + if (autoUpdateRender) useTicker = true; } /// Utility method used by the [SceneBuilderWidget] to set the flag /// `CustomPaint.willChange` /// bool painterMightChange() { - if ((useTicker ?? false) || - (autoUpdateRender ?? false) || - (usePointer ?? false) || - (useKeyboard ?? false)) { + if (useTicker || autoUpdateRender || usePointer || useKeyboard) { return true; } - return painterWillChange ?? false; + return painterWillChange; } } diff --git a/lib/src/core/scene_controller.dart b/lib/src/core/scene_controller.dart index 8271623..22ed664 100644 --- a/lib/src/core/scene_controller.dart +++ b/lib/src/core/scene_controller.dart @@ -38,19 +38,18 @@ class SceneController { /// Access the keyboard manager instance associated with this /// [SceneController]. - KeyboardManager? get keyboard => _keyboard; + KeyboardManager get keyboard => _keyboard; /// Access the pointer manager instance associated with this /// [SceneController]. - PointerManager? get pointer => _pointer; + PointerManager get pointer => _pointer; - KeyboardManager? _keyboard; - - PointerManager? _pointer; + late KeyboardManager _keyboard; + late PointerManager _pointer; GTicker? _ticker; - InputConverter? $inputConverter; + late InputConverter $inputConverter; SceneConfig get config => _config; @@ -65,13 +64,13 @@ class SceneController { bool _isInited = false; set config(SceneConfig sceneConfig) { - _config.rebuildOnHotReload = sceneConfig.rebuildOnHotReload ?? true; - _config.autoUpdateRender = sceneConfig.autoUpdateRender ?? true; - _config.isPersistent = sceneConfig.isPersistent ?? false; - _config.painterWillChange = sceneConfig.painterWillChange ?? true; - _config.useKeyboard = sceneConfig.useKeyboard ?? false; - _config.usePointer = sceneConfig.usePointer ?? false; - _config.useTicker = sceneConfig.useTicker ?? false; + _config.rebuildOnHotReload = sceneConfig.rebuildOnHotReload; + _config.autoUpdateRender = sceneConfig.autoUpdateRender; + _config.isPersistent = sceneConfig.isPersistent; + _config.painterWillChange = sceneConfig.painterWillChange; + _config.useKeyboard = sceneConfig.useKeyboard; + _config.usePointer = sceneConfig.usePointer; + _config.useTicker = sceneConfig.useTicker; } /// constructor. @@ -87,7 +86,7 @@ class SceneController { if (front != null) { frontScene = ScenePainter(this, front); } - this.config = config ?? SceneConfig.defaultConfig; + this.config = config??SceneConfig.defaultConfig; } /// WARNING: Internal method @@ -109,7 +108,7 @@ class SceneController { } void setup() { - if (!GTween.initialized) { + if (!GTween.initializedCommonWraps) { GTween.registerCommonWraps(); } backScene?.$setup(); @@ -129,7 +128,7 @@ class SceneController { } void dispose() { - if (_config.isPersistent ?? false) { + if (_config.isPersistent) { return; } _onHotReload?.removeAll(); @@ -145,20 +144,24 @@ class SceneController { CustomPainter? buildFrontPainter() => frontScene?.buildPainter(); void _initInput() { - if (_config.useKeyboard ?? false) { - _keyboard ??= KeyboardManager(); - } - if (_config.usePointer ?? false) { - _pointer ??= PointerManager(); - } - if (_config.useKeyboard ?? false || (_config.usePointer ?? false)) { - $inputConverter ??= InputConverter(_pointer, _keyboard); - } + // if (_config.useKeyboard) { + // _keyboard ??= KeyboardManager(); + // } + // if (_config.usePointer) { + // _pointer ??= PointerManager(); + // } + + _keyboard = KeyboardManager(); + _pointer = PointerManager(); + // if (_config.useKeyboard ?? false || (_config.usePointer ?? false)) { + // trace("CREATE INPUT!"); + // } + $inputConverter = InputConverter(_pointer, _keyboard); } void reassembleWidget() { _onHotReload?.dispatch(); - if (_config.rebuildOnHotReload ?? false) { + if (_config.rebuildOnHotReload) { GTween.hotReload(); dispose(); @@ -173,5 +176,5 @@ class SceneController { bool _anySceneAutoUpdate() => _sceneAutoUpdate(backScene) || _sceneAutoUpdate(frontScene); - bool _hasTicker() => _anySceneAutoUpdate() || (_config.useTicker ?? false); + bool _hasTicker() => _anySceneAutoUpdate() || _config.useTicker; } diff --git a/lib/src/core/scene_painter.dart b/lib/src/core/scene_painter.dart index caa4412..edca8a8 100644 --- a/lib/src/core/scene_painter.dart +++ b/lib/src/core/scene_painter.dart @@ -101,7 +101,7 @@ class ScenePainter with EventDispatcherMixin { makeCurrent(); /// If needed, can be overridden later by the [root]. - autoUpdateAndRender = core.config.autoUpdateRender ?? false; + autoUpdateAndRender = core.config.autoUpdateRender; } void _createPicture() { @@ -201,7 +201,7 @@ class ScenePainter with EventDispatcherMixin { } void _initMouseInput() { - core.pointer?.onInput.add(_onInputHandler); + core.pointer.onInput.add(_onInputHandler); } void _onInputHandler(PointerEventData e) { @@ -242,13 +242,13 @@ class ScenePainter with EventDispatcherMixin { _isReady = false; size = Size.zero; _stage?.dispose(); - core.pointer?.onInput.remove(_onInputHandler); + core.pointer.onInput.remove(_onInputHandler); _onUpdate?.removeAll(); _onUpdate = null; super.dispose(); } - bool get _hasPointer => core.pointer?.onInput != null; + bool get _hasPointer => core.pointer.onInput != null; bool shouldRepaint() => needsRepaint; } diff --git a/lib/src/display/stage.dart b/lib/src/display/stage.dart index 791ac7d..0ef8659 100644 --- a/lib/src/display/stage.dart +++ b/lib/src/display/stage.dart @@ -214,8 +214,8 @@ class Stage extends GDisplayObjectContainer void dispose() { _size = null; _backgroundPaint = null; - scene.core.pointer?.dispose(); - scene.core.keyboard?.dispose(); + scene.core.pointer.dispose(); + scene.core.keyboard.dispose(); $disposeResizeSignals(); $disposeTickerSignals(); $disposeStagePointerSignals(); diff --git a/lib/src/display/text.dart b/lib/src/display/text.dart index 0b3bf2c..afb42e3 100644 --- a/lib/src/display/text.dart +++ b/lib/src/display/text.dart @@ -218,7 +218,7 @@ class GText extends GDisplayObject { void _layout() { //// Web has a bug for double.infinity for text layout. - var paragraphWidth = !SystemUtils.usingSkia ? _maxTextWidthForWeb : _width; + final paragraphWidth = _width.isInfinite && !SystemUtils.usingSkia ? _maxTextWidthForWeb : _width; _paragraph?.layout(ui.ParagraphConstraints(width: paragraphWidth)); _invalidSize = false; } diff --git a/lib/src/input/input_converter.dart b/lib/src/input/input_converter.dart index 8f85cd6..f7249f8 100644 --- a/lib/src/input/input_converter.dart +++ b/lib/src/input/input_converter.dart @@ -2,34 +2,34 @@ import 'package:flutter/gestures.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; +import '../../graphx.dart'; import '../events/keyboard_data.dart'; import '../events/pointer_data.dart'; import 'keyboard_manager.dart'; import 'pointer_manager.dart'; class InputConverter { - final PointerManager? pointer; - final KeyboardManager? keyboard; - + final PointerManager pointer; + final KeyboardManager keyboard; InputConverter(this.pointer, this.keyboard); /// mouse stuffs. void pointerEnter(PointerEnterEvent event) { - pointer!.$process(PointerEventData( + pointer.$process(PointerEventData( type: PointerEventType.enter, rawEvent: event, )); } void pointerExit(PointerExitEvent event) { - pointer!.$process(PointerEventData( + pointer.$process(PointerEventData( type: PointerEventType.exit, rawEvent: event, )); } void pointerHover(PointerHoverEvent event) { - pointer!.$process(PointerEventData( + pointer.$process(PointerEventData( type: PointerEventType.hover, rawEvent: event, )); @@ -38,35 +38,35 @@ class InputConverter { /// touchable stuffs. void pointerSignal(PointerSignalEvent event) { - pointer!.$process(PointerEventData( + pointer.$process(PointerEventData( type: PointerEventType.scroll, rawEvent: event as PointerScrollEvent, )); } void pointerMove(PointerMoveEvent event) { - pointer!.$process(PointerEventData( + pointer.$process(PointerEventData( type: PointerEventType.move, rawEvent: event, )); } void pointerCancel(PointerCancelEvent event) { - pointer!.$process(PointerEventData( + pointer.$process(PointerEventData( type: PointerEventType.cancel, rawEvent: event, )); } void pointerUp(PointerUpEvent event) { - pointer!.$process(PointerEventData( + pointer.$process(PointerEventData( type: PointerEventType.up, rawEvent: event, )); } void pointerDown(PointerDownEvent event) { - pointer!.$process(PointerEventData( + pointer.$process(PointerEventData( type: PointerEventType.down, rawEvent: event, )); @@ -74,7 +74,7 @@ class InputConverter { void handleKey(RawKeyEvent event) { final isDown = event is RawKeyDownEvent; - keyboard!.$process(KeyboardEventData( + keyboard.$process(KeyboardEventData( type: isDown ? KeyEventType.down : KeyEventType.up, rawEvent: event, )); diff --git a/lib/src/log/trace.dart b/lib/src/log/trace.dart index 040c1e9..ca64378 100644 --- a/lib/src/log/trace.dart +++ b/lib/src/log/trace.dart @@ -44,16 +44,16 @@ void traceConfig({ /// object to be printed. The way trace() shows output in the console can be /// defined with [traceConfig()]. void trace( - Object arg1, [ - Object? arg2, - Object? arg3, - Object? arg4, - Object? arg5, - Object? arg6, - Object? arg7, - Object? arg8, - Object? arg9, - Object? arg10, + dynamic arg1, [ + dynamic? arg2, + dynamic? arg3, + dynamic? arg4, + dynamic? arg5, + dynamic? arg6, + dynamic? arg7, + dynamic? arg8, + dynamic? arg9, + dynamic? arg10, ]) { ++_traceCount; final outputList = [ diff --git a/lib/src/render/graphics.dart b/lib/src/render/graphics.dart index 7e1478d..f109280 100644 --- a/lib/src/render/graphics.dart +++ b/lib/src/render/graphics.dart @@ -1,6 +1,8 @@ import 'dart:typed_data'; import 'dart:ui' as ui; + import 'package:flutter/painting.dart'; + import '../../graphx.dart'; enum GradientType { @@ -109,8 +111,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { return this; } - Graphics beginBitmapFill( - GTexture texture, [ + Graphics beginBitmapFill(GTexture texture, [ GMatrix? matrix, bool repeat = false, bool smooth = false, @@ -144,7 +145,8 @@ class Graphics with RenderUtilMixin implements GxRenderable { } Graphics drawPicture(ui.Picture picture) { - _drawingQueue.add(GraphicsDrawingData()..picture = picture); + _drawingQueue.add(GraphicsDrawingData() + ..picture = picture); return this; } @@ -185,24 +187,23 @@ class Graphics with RenderUtilMixin implements GxRenderable { /// For [GradientType.radial], `end` is used for [RadialGradient.focal], check /// the [RadialGradient] docs to understand the relation with [focalRadius] - Graphics beginGradientFill( - GradientType type, - List colors, { - List? ratios, - Alignment? begin, - Alignment? end, - double rotation = 0, - TileMode tileMode = TileMode.clamp, - Rect? gradientBox, - - /// only radial - double radius = 0.5, - double focalRadius = 0.0, - - /// only sweep - double sweepStartAngle = 0.0, - double sweepEndAngle = 6.2832, - }) { + Graphics beginGradientFill(GradientType type, + List colors, { + List? ratios, + Alignment? begin, + Alignment? end, + double rotation = 0, + TileMode tileMode = TileMode.clamp, + Rect? gradientBox, + + /// only radial + double radius = 0.5, + double focalRadius = 0.0, + + /// only sweep + double sweepStartAngle = 0.0, + double sweepEndAngle = 6.2832, + }) { final gradient = _createGradient( type, colors, @@ -228,23 +229,22 @@ class Graphics with RenderUtilMixin implements GxRenderable { return this; } - Gradient _createGradient( - GradientType type, - List colors, [ - List? ratios, - Alignment? begin, - Alignment? end, - double rotation = 0, - - /// only radial - double radius = 0.5, - double focalRadius = 0.0, - - /// only sweep - double sweepStartAngle = 0.0, - double sweepEndAngle = 6.2832, - TileMode tileMode = TileMode.clamp, - ]) { + Gradient _createGradient(GradientType type, + List colors, [ + List? ratios, + Alignment? begin, + Alignment? end, + double rotation = 0, + + /// only radial + double radius = 0.5, + double focalRadius = 0.0, + + /// only sweep + double sweepStartAngle = 0.0, + double sweepEndAngle = 6.2832, + TileMode tileMode = TileMode.clamp, + ]) { final transform = GradientRotation(rotation); if (type == GradientType.radial) { return RadialGradient( @@ -284,29 +284,28 @@ class Graphics with RenderUtilMixin implements GxRenderable { /// Also for `GradientType.radial`, `Alignment end` represents the focalPoint. /// So make sure to increase the `radius` if you use a focalPoint alignment /// different than the center (meaning `begin!=end`). - Graphics lineGradientStyle( - GradientType type, - List colors, { - List? ratios, - Alignment? begin, - Alignment? end, - double rotation = 0, - - /// only `GradientType.radial` - double radius = 0.5, - double focalRadius = 0.0, - - /// only `GradientType.sweep` - double sweepStartAngle = 0.0, - double sweepEndAngle = 6.2832, - - /// manually define the bounding box of the Gradient shader. - Rect? gradientBox, - - /// when the gradient box is different than the object bounds, you can - /// see the `tileMode` behaviour. - TileMode tileMode = TileMode.clamp, - }) { + Graphics lineGradientStyle(GradientType type, + List colors, { + List? ratios, + Alignment? begin, + Alignment? end, + double rotation = 0, + + /// only `GradientType.radial` + double radius = 0.5, + double focalRadius = 0.0, + + /// only `GradientType.sweep` + double sweepStartAngle = 0.0, + double sweepEndAngle = 6.2832, + + /// manually define the bounding box of the Gradient shader. + Rect? gradientBox, + + /// when the gradient box is different than the object bounds, you can + /// see the `tileMode` behaviour. + TileMode tileMode = TileMode.clamp, + }) { /// actual paint must be stroke. assert(_currentDrawing!.fill!.style == PaintingStyle.stroke); @@ -331,8 +330,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { return this; } - Graphics lineBitmapStyle( - GTexture texture, [ + Graphics lineBitmapStyle(GTexture texture, [ GMatrix? matrix, bool repeat = true, bool smooth = false, @@ -369,37 +367,32 @@ class Graphics with RenderUtilMixin implements GxRenderable { return this; } - Graphics cubicCurveTo( - double controlX1, - double controlY1, - double controlX2, - double controlY2, - double anchorX, - double anchorY, - ) { + Graphics cubicCurveTo(double controlX1, + double controlY1, + double controlX2, + double controlY2, + double anchorX, + double anchorY,) { _path! .cubicTo(controlX1, controlY1, controlX2, controlY2, anchorX, anchorY); return this; } - Graphics curveTo( - double controlX, - double controlY, - double anchorX, - double anchorY, - ) { + Graphics curveTo(double controlX, + double controlY, + double anchorX, + double anchorY,) { _path!.quadraticBezierTo(controlX, controlY, anchorX, anchorY); return this; } - Graphics conicCurveTo( - double controlX, - double controlY, - double anchorX, - double anchorY, - double weight, [ - bool relative = false, - ]) { + Graphics conicCurveTo(double controlX, + double controlY, + double anchorX, + double anchorY, + double weight, [ + bool relative = false, + ]) { if (!relative) { _path!.conicTo(controlX, controlY, anchorX, anchorY, weight); } else { @@ -438,16 +431,15 @@ class Graphics with RenderUtilMixin implements GxRenderable { return this; } - Graphics drawRoundRectComplex( - double x, - double y, - double width, - double height, [ - double topLeftRadius = 0, - double topRightRadius = 0, - double bottomLeftRadius = 0, - double bottomRightRadius = 0, - ]) { + Graphics drawRoundRectComplex(double x, + double y, + double width, + double height, [ + double topLeftRadius = 0, + double topRightRadius = 0, + double bottomLeftRadius = 0, + double bottomRightRadius = 0, + ]) { _path!.addRRect( RRect.fromLTRBAndCorners( x, @@ -463,14 +455,13 @@ class Graphics with RenderUtilMixin implements GxRenderable { return this; } - Graphics drawRoundRect( - double x, - double y, - double width, - double height, - double ellipseWidth, [ - double? ellipseHeight, - ]) { + Graphics drawRoundRect(double x, + double y, + double width, + double height, + double ellipseWidth, [ + double? ellipseHeight, + ]) { final r = RRect.fromLTRBXY( x, y, @@ -504,14 +495,12 @@ class Graphics with RenderUtilMixin implements GxRenderable { } } - Graphics arcOval( - double cx, - double cy, - double radiusX, - double radiusY, - double startAngle, - double sweepAngle, - ) { + Graphics arcOval(double cx, + double cy, + double radiusX, + double radiusY, + double startAngle, + double sweepAngle,) { _path!.addArc( Rect.fromCenter( center: Offset(cx, cy), @@ -524,14 +513,13 @@ class Graphics with RenderUtilMixin implements GxRenderable { return this; } - Graphics arc( - double cx, - double cy, - double radius, - double startAngle, - double sweepAngle, [ - bool moveTo = false, - ]) { + Graphics arc(double cx, + double cy, + double radius, + double startAngle, + double sweepAngle, [ + bool moveTo = false, + ]) { if (sweepAngle == 0) return this; if (!moveTo) { _path!.arcTo( @@ -550,15 +538,14 @@ class Graphics with RenderUtilMixin implements GxRenderable { return this; } - Graphics arcToPoint( - double endX, - double endY, - double radius, [ - double rotation = 0.0, - bool largeArc = false, - bool clockwise = true, - bool relativeMoveTo = false, - ]) { + Graphics arcToPoint(double endX, + double endY, + double radius, [ + double rotation = 0.0, + bool largeArc = false, + bool clockwise = true, + bool relativeMoveTo = false, + ]) { if (radius == 0) return this; if (relativeMoveTo) { _path!.arcToPoint( @@ -581,13 +568,12 @@ class Graphics with RenderUtilMixin implements GxRenderable { return this; } - Graphics drawPolygonFaces( - double x, - double y, - double radius, - int sides, [ - double rotation = 0, - ]) { + Graphics drawPolygonFaces(double x, + double y, + double radius, + int sides, [ + double rotation = 0, + ]) { final points = List.filled(sides, Offset(0, 0)); final rel = 2 * Math.PI / sides; for (var i = 1; i <= sides; ++i) { @@ -599,14 +585,13 @@ class Graphics with RenderUtilMixin implements GxRenderable { return this; } - Graphics drawStar( - double x, - double y, - int points, - double radius, [ - double? innerRadius, - double rotation = 0, - ]) { + Graphics drawStar(double x, + double y, + int points, + double radius, [ + double? innerRadius, + double rotation = 0, + ]) { innerRadius ??= radius / 2; final startAngle = (-1 * Math.PI1_2) + rotation; final len = points * 2; @@ -629,7 +614,8 @@ class Graphics with RenderUtilMixin implements GxRenderable { Graphics beginHole() { if (_holeMode) return this; _holeMode = true; - _currentDrawing = GraphicsDrawingData(null, Path())..isHole = true; + _currentDrawing = GraphicsDrawingData(null, Path()) + ..isHole = true; return this; } @@ -702,7 +688,6 @@ class Graphics with RenderUtilMixin implements GxRenderable { _constrainAlpha(); if (!_isVisible) return; - // trace("en", _drawingQueue.length); for (var graph in _drawingQueue) { if (graph!.hasPicture) { canvas!.drawPicture(graph.picture!); @@ -777,8 +762,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { /// This should be used only if you are operating with `Path` and `Paint` /// directly. /// `x` and `y` can shift the Path coordinates. - void pushData( - GraphicsDrawingData data, [ + void pushData(GraphicsDrawingData data, [ bool asCurrent = false, double? x, double? y, @@ -812,8 +796,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { /// Appends a native `Path` to the current drawing path, /// `x` and `y` can offset the target position, while `transform` can be used /// to rotated, scale, translate, the given shape. - Graphics drawPath( - Path path, [ + Graphics drawPath(Path path, [ double x = 0, double y = 0, GMatrix? transform, @@ -821,7 +804,9 @@ class Graphics with RenderUtilMixin implements GxRenderable { _path!.addPath( path, Offset(x, y), - matrix4: transform?.toNative()?.storage, + matrix4: transform + ?.toNative() + ?.storage, ); return this; } @@ -829,8 +814,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { /// Draw a bunch of triangles in the Canvas, only supports /// solid fill or image (not a stroke). /// Doesn't use a Path(), but drawVertices()... - Graphics drawTriangles( - List vertices, [ + Graphics drawTriangles(List vertices, [ List? indices, List? uvtData, List? hexColors, @@ -920,7 +904,8 @@ extension ExtSkiaPaintCustom on Paint { } class _GraphVertices { - List? vertices, uvtData, adjustedUvtData; + List vertices; + List?uvtData, adjustedUvtData; List? colors, indices; BlendMode? blendMode; VertexMode? mode; @@ -940,24 +925,23 @@ class _GraphVertices { Culling culling; /// check if uvt requires normalization. - _GraphVertices( - this.mode, - this.vertices, [ - this.indices, - this.uvtData, - this.colors, - this.blendMode = BlendMode.src, - this.culling = Culling.positive, - ]) { + _GraphVertices(this.mode, + this.vertices, [ + this.indices, + this.uvtData, + this.colors, + this.blendMode = BlendMode.src, + this.culling = Culling.positive, + ]) { _normalizedUvt = false; - final len = uvtData!.length; + final len = uvtData?.length ?? 0; if (uvtData != null && len > 6) { for (var i = 0; i < 6; ++i) { - if (uvtData![i]! <= 2.0) { + if (uvtData![i] <= 2.0) { _normalizedUvt = true; } } - if (uvtData![len - 2]! <= 2.0 || uvtData![len - 1]! <= 2.0) { + if (uvtData![len - 2] <= 2.0 || uvtData![len - 1] <= 2.0) { _normalizedUvt = true; } } @@ -1007,19 +991,20 @@ class _GraphVertices { adjustedUvtData = uvtData; } else { /// make a ratio of the image size - var imgW = shaderTexture!.width; - var imgH = shaderTexture.height; - adjustedUvtData = List.filled(uvtData!.length, null); + final imgW = shaderTexture!.width ?? 0; + final imgH = shaderTexture.height ?? 0; + adjustedUvtData = List.filled(uvtData!.length, 0.0); for (var i = 0; i < uvtData!.length; i += 2) { - adjustedUvtData![i] = uvtData![i]! * imgW!; - adjustedUvtData![i + 1] = uvtData![i + 1]! * imgH!; + adjustedUvtData![i] = uvtData![i] * imgW; + adjustedUvtData![i + 1] = uvtData![i + 1] * imgH; } } } void calculateCulling() { var i = 0; - var offsetX = 0.0, offsetY = 0.0; + var offsetX = 0.0, + offsetY = 0.0; var ind = indices; var v = vertices; var l = indices!.length; @@ -1035,12 +1020,12 @@ class _GraphVertices { var icx = ind[_c] * 2; var icy = ind[_c] * 2 + 1; - var x1 = v![iax]! - offsetX; - var y1 = v[iay]! - offsetY; - var x2 = v[ibx]! - offsetX; - var y2 = v[iby]! - offsetY; - var x3 = v[icx]! - offsetX; - var y3 = v[icy]! - offsetY; + var x1 = v[iax] - offsetX; + var y1 = v[iay] - offsetY; + var x2 = v[ibx] - offsetX; + var y2 = v[iby] - offsetY; + var x3 = v[icx] - offsetX; + var y3 = v[icy] - offsetY; switch (culling) { case Culling.positive: @@ -1067,14 +1052,12 @@ class _GraphVertices { } class _GraphUtils { - static bool isCCW( - double x1, - double y1, - double x2, - double y2, - double x3, - double y3, - ) => + static bool isCCW(double x1, + double y1, + double x2, + double y2, + double x3, + double y3,) => ((x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1)) < 0; // static List colorsFromHex(List colors, List alphas) { @@ -1091,11 +1074,11 @@ class _GraphUtils { static Path getPathFromVertices(_GraphVertices v) { var path = _helperPath; path.reset(); - var pos = v.vertices!; + final pos = v.vertices; var len = pos.length; final points = []; for (var i = 0; i < len; i += 2) { - points.add(Offset(pos[i]!, pos[i + 1]!)); + points.add(Offset(pos[i], pos[i + 1])); } path.addPolygon(points, true); return path; @@ -1106,8 +1089,8 @@ class _GraphUtils { var ind = v.indices; if (ind == null) { /// calculate - var len = ver!.length; - var out = List.filled(len * 2, null); + var len = ver.length; + var out = List.filled(len * 2, 0.0); var j = 0; for (var i = 0; i < len; i += 6) { out[j++] = ver[i + 0]; @@ -1126,7 +1109,7 @@ class _GraphUtils { return out; } else { var len = ind.length; - var out = List.filled(len * 4, null); + var out = List.filled(len * 4, 0.0); var j = 0; for (var i = 0; i < len; i += 3) { var i0 = ind[i + 0]; @@ -1135,7 +1118,7 @@ class _GraphUtils { var v0 = i0 * 2; var v1 = i1 * 2; var v2 = i2 * 2; - out[j++] = ver![v0]; + out[j++] = ver[v0]; out[j++] = ver[v0 + 1]; out[j++] = ver[v1]; out[j++] = ver[v1 + 1]; diff --git a/lib/src/tween/src/gtween.dart b/lib/src/tween/src/gtween.dart index c84dccc..74a4394 100644 --- a/lib/src/tween/src/gtween.dart +++ b/lib/src/tween/src/gtween.dart @@ -102,7 +102,7 @@ class GTween { /// ); /// ``` static void registerCommonWraps([List? otherWraps]) { - if (initialized) return; + if (initializedCommonWraps) return; GTween.registerWrap(GTweenableDisplayObject.wrap); GTween.registerWrap(GTweenableMap.wrap); GTween.registerWrap(GTweenableDouble.wrap); @@ -111,7 +111,7 @@ class GTween { GTween.registerWrap(GTweenableList.wrap); // GTween.registerWrap(GTweenableColor.wrap); otherWraps?.forEach(GTween.registerWrap); - initialized = true; + initializedCommonWraps = true; } static void hotReload() { @@ -133,8 +133,8 @@ class GTween { _lastFrameTimeStamp = ts; } - static bool initialized = false; - + static bool initializedEngine = false; + static bool initializedCommonWraps = false; static double _time = 0; static double _frame = 0; @@ -147,11 +147,29 @@ class GTween { static void registerWrap(GxAnimatableBuilder builder) => _tweenableBuilders.add(builder); - static Map? _reservedProps; + static void _initEngine() { + initializedEngine = true; + _time = getTimer() / 1000; + _frame = 0; + ticker.add(_updateRoot); + } + + static final Map _reservedProps = { + 'delay': 1, + 'ease': 1, + 'usedFrames': 1, + 'overwrite': 1, + 'onComplete': 1, + 'runBackwards': 1, + 'immediateRender': 1, + 'onUpdate': 1, + 'startAt': 1, + }; + static GTween? _first; static GTween? _last; - double? _duration; + late double _duration; Map? vars; late GVars nanoVars; late double _startTime; @@ -164,7 +182,7 @@ class GTween { late bool _useFrames; double? ratio = 0; - Function? _ease; + late Function _ease; // Ease _rawEase; bool _inited = false; @@ -177,22 +195,7 @@ class GTween { bool _gc = false; GTween(this.target, double duration, this.vars, [GVars? myVars]) { - if (_reservedProps == null) { - _reservedProps = { - 'delay': 1, - 'ease': 1, - 'usedFrames': 1, - 'overwrite': 1, - 'onComplete': 1, - 'runBackwards': 1, - 'immediateRender': 1, - 'onUpdate': 1, - 'startAt': 1, - }; - _time = getTimer() / 1000; - _frame = 0; - ticker.add(_updateRoot); - } + if (!GTween.initializedEngine) GTween._initEngine(); nanoVars = myVars ?? GVars(); nanoVars.defaults(); @@ -230,7 +233,7 @@ class GTween { } // _rawEase = nanoVars.ease; // _ease = _rawEase?.getRatio; - _ease = nanoVars.ease; + _ease = nanoVars.ease ?? GTween.defaultEase; _useFrames = nanoVars.useFrames ?? false; _startTime = (_useFrames ? _frame : _time) + (nanoVars.delay ?? 0); @@ -241,19 +244,19 @@ class GTween { killTweensOf(target); } } - _prev = _last; - if (_last != null) { - _last!._next = this; + _prev = GTween._last; + if (GTween._last != null) { + GTween._last!._next = this; } else { - _first = this; + GTween._first = this; } - _last = this; + GTween._last = this; if (nanoVars.immediateRender! || (duration == 0 && nanoVars.delay == 0 && nanoVars.immediateRender != false)) { - _render(0); + _render(0.0); } } @@ -287,10 +290,13 @@ class GTween { if (target == null) return; for (final key in vars!.keys) { final prop = '$key'; - if (!_reservedProps!.containsKey(prop)) { + if (!GTween._reservedProps.containsKey(prop)) { _firstPT = PropTween( - target: target as GTweenable?, property: key, next: _firstPT); - var startVal = _getStartValue(target, key); + target: target as GTweenable, + property: key, + next: _firstPT, + ); + final startVal = _getStartValue(target, key); _firstPT!.s = startVal; var endValue = _getEndValue(vars!, key, _firstPT!.s); _firstPT!.cObj = vars![key]; @@ -325,7 +331,7 @@ class GTween { void _setCurrentValue(PropTween pt, double ratio) { var value = pt.c! * ratio + pt.s; if (pt.t is GTweenable) { - pt.t!.setProperty(pt.p, value); + pt.t!.setProperty(pt.p!, value); } else { pt.t![pt.p as String] = value; } @@ -337,16 +343,16 @@ class GTween { } else if (t is Map) { return t[prop]; } - throw 'error'; + throw 'GTween Error: property not found.'; } - void _render(double? time) { + void _render(double time) { if (!_inited) { _init(); - time = 0; + time = 0.0; } var prevTime = time; - if (time! >= _duration!) { + if (time >= _duration) { time = _duration; ratio = 1; } else if (time <= 0) { @@ -356,7 +362,7 @@ class GTween { ratio = 0; } else { // ratio = _ease.getRatio(time / _duration); - ratio = _ease!(time / _duration!); + ratio = _ease(time / _duration); } var pt = _firstPT; @@ -508,11 +514,11 @@ class GTween { _frame += 1; // _time = getTimer() * .001; if (delta <= 0) delta = .016; - _time += delta * timeScale; - var tween = _first; + GTween._time += delta * GTween.timeScale; + var tween = GTween._first; while (tween != null) { var next = tween._next; - var t = tween._useFrames ? _frame : _time; + double t = tween._useFrames ? GTween._frame : GTween._time; if (t >= tween._startTime && !tween._gc) { tween._render(t - tween._startTime); } diff --git a/lib/src/tween/src/mixins/tweenable.dart b/lib/src/tween/src/mixins/tweenable.dart index 1fe63c6..04561cf 100644 --- a/lib/src/tween/src/mixins/tweenable.dart +++ b/lib/src/tween/src/mixins/tweenable.dart @@ -30,8 +30,9 @@ mixin GTweenable { /// override to know which properties will change. void setTweenProp(PropTween tweenProp) { - final lerpObj = _lerps[tweenProp.p as String]; - if (lerpObj == null) return; + final key = '${tweenProp.p}'; + if( !_lerps.containsKey(key)) return ; + final lerpObj = _lerps[key]!; lerpObj.to = tweenProp.cObj; tweenProp.c = 1.0; } @@ -55,14 +56,21 @@ mixin GTweenable { /// implement in class. Map>? getTweenableAccessors() => null; - void setProperty(Object? prop, double value) { - if (_lerps[prop as String] != null) { - _lerps[prop]!.resolve(value); - // TODO: add setLerp(prop, value) function to be override? + void setProperty(Object prop, double value) { + final key = '$prop'; + if (_lerps.containsKey(key)){ + _lerps[key]?.resolve(value); } else { if (_accessors == null) initProps(); - _accessors![prop]![1](value); + _accessors![key]![1](value); } + // if (_lerps[prop as String] != null) { + // _lerps[prop]!.resolve(value); + // // TODO: add setLerp(prop, value) function to be override? + // } else { + // if (_accessors == null) initProps(); + // _accessors![prop]![1](value); + // } } double getProperty(Object prop) { @@ -83,5 +91,5 @@ mixin GTweenable { double? operator [](String key) => getProperty(key); - void operator []=(String? key, double value) => setProperty(key, value); + void operator []=(String key, double value) => setProperty(key, value); } diff --git a/lib/src/tween/src/wraps/common_wraps.dart b/lib/src/tween/src/wraps/common_wraps.dart index c16b212..527c40e 100644 --- a/lib/src/tween/src/wraps/common_wraps.dart +++ b/lib/src/tween/src/wraps/common_wraps.dart @@ -145,14 +145,16 @@ class GTweenableList with GTweenable { } @override - void setProperty(Object? prop, double val) { + void setProperty(Object prop, double val) { final index = int.tryParse('$prop')!; value[index] = convertFromDouble(value[index], val); } @override double getProperty(Object prop) { - return convertToDouble(value[int.parse('$prop')]); + final idx = int.parse('$prop'); + final output = convertToDouble(value[idx]); + return output; } GTween tween( diff --git a/lib/src/widgets/graphx_widget.dart b/lib/src/widgets/graphx_widget.dart index 0d77d6d..7e322d8 100644 --- a/lib/src/widgets/graphx_widget.dart +++ b/lib/src/widgets/graphx_widget.dart @@ -48,7 +48,6 @@ class _SceneBuilderWidgetState extends State { GRect? _getRenderObjectWindowBounds() { if (!mounted) return null; - trace(context); return ContextUtils.getRenderObjectBounds(context); } @@ -81,30 +80,30 @@ class _SceneBuilderWidgetState extends State { ); var converter = _controller.$inputConverter; - if (_controller.config.usePointer ?? false) { + if (_controller.config.usePointer) { child = MouseRegion( - onEnter: converter?.pointerEnter, - onExit: converter?.pointerExit, - onHover: converter?.pointerHover, + onEnter: converter.pointerEnter, + onExit: converter.pointerExit, + onHover: converter.pointerHover, cursor: MouseCursor.defer, opaque: widget.mouseOpaque, child: Listener( child: child, behavior: widget.pointerBehaviour, - onPointerDown: converter?.pointerDown, - onPointerUp: converter?.pointerUp, - onPointerCancel: converter?.pointerCancel, - onPointerMove: converter?.pointerMove, - onPointerSignal: converter?.pointerSignal, + onPointerDown: converter.pointerDown, + onPointerUp: converter.pointerUp, + onPointerCancel: converter.pointerCancel, + onPointerMove: converter.pointerMove, + onPointerSignal: converter.pointerSignal, ), ); } - if (_controller.config.useKeyboard ?? false) { + if (_controller.config.useKeyboard) { child = RawKeyboardListener( - onKey: converter!.handleKey, + onKey: converter.handleKey, autofocus: true, includeSemantics: false, - focusNode: converter.keyboard?.focusNode ?? FocusNode(), + focusNode: converter.keyboard.focusNode, child: child, ); } diff --git a/pubspec.lock b/pubspec.lock index 7efaa62..1aa1395 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -73,7 +73,7 @@ packages: name: http url: "https://pub.dartlang.org" source: hosted - version: "0.13.0" + version: "0.13.1" http_parser: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 5b7ff0a..bc79318 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: graphx description: Render API on top of CustomPainter to power-up your Flutter apps to the next level. -version: 0.9.9 +version: 1.0.0-nullsafety.0 homepage: https://github.com/roipeker/graphx environment: @@ -9,8 +9,8 @@ environment: dependencies: flutter: sdk: flutter - xml: ^5.0.0-nullsafety.1 - http: ^0.13.0-nullsafety.0 + xml: ^5.0.2 + http: ^0.13.1 flutter_svg: ^0.21.0-nullsafety.0 dev_dependencies: