Giter Site home page Giter Site logo

rodydavis / flutter_implicit_animations Goto Github PK

View Code? Open in Web Editor NEW
37.0 3.0 0.0 6.06 MB

Flutter animations every frame

Home Page: https://rodydavis.github.io/flutter_implicit_animations/

License: Apache License 2.0

Kotlin 0.28% Swift 2.25% Objective-C 0.07% Dart 13.99% CMake 36.37% C++ 40.67% C 2.76% HTML 3.60%
animation flutter game-logic game-loop games

flutter_implicit_animations's Introduction

Flutter implicit animations

Live Demo

Problem

There are a few options with flutter when creating animations:

  • AnimationController
  • AnimatedWidget and other AnimatedX classes
  • Animations package

This solutions all solve a variety of problems and can solve certain use cases.

When building animations you want to do a piece of work every frame and animated it

The build method already does a great job of rendering the state synchronously and will cache widgets that have not changed.

Solution

This example aims to build animations in a game-like loop with a update, paint and start callback.

class SimpleExample extends StatefulWidget {
  const SimpleExample({Key? key}) : super(key: key);

  @override
  State<SimpleExample> createState() => _SimpleExampleState();
}

class _SimpleExampleState extends AnimatedState<SimpleExample> {
  var x = 0.0;
  var y = 0.0;
  var z = 0.0;

  @override
  void update(Duration time) {
    final t = delta.inMilliseconds / 1000;
    x += t;
    y += t;
    z += t;
  }

  @override
  Widget paint(BuildContext context, BoxConstraints constraints) {
    return Material(
      child: Center(
        child: Container(
          width: 100,
          height: 100,
          transform: Matrix4.identity()
            ..rotateX(x)
            ..rotateY(y)
            ..rotateZ(z),
          child: const Text(
            'Hello World',
            style: TextStyle(
              fontSize: 30,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      ),
    );
  }
}

By only changing State to AnimatedState and the build method to paint method with constraints it is possible to draw every frame.

This also makes it possible to animate multiple things at once and update asynchronously.

Inline painter

There is also a helper class I use a lot to render a inline canvas.

CustomPaint(
  painter: InlinePainter(
    draw: (canvas, size) {
      final paint = Paint()
      ..color = cube.color
      ..style = PaintingStyle.fill
      ..strokeWidth = 2;
      final rect = Rect.fromLTWH(0, 0, size.width, size.height);
      canvas.drawRect(rect, paint);
    },
  ),
)

Example

import 'dart:math';

import 'package:flutter/material.dart';

import '../widgets/animation.dart';
import '../widgets/inline_painter.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends AnimatedState<HomeScreen> {
  final List<Cube> cubes = <Cube>[];

  double x = 0.0, y = 0.0, z = 0.0;
  Color color = Colors.red;
  Offset offset = Offset.zero;

  void addCube(Size size) {
  final randomOffset = Offset(
    Random().nextDouble() * size.width,
    Random().nextDouble() * size.height,
  );
  final randomDelta = Random().nextDouble() * 20;
  final randomDirection = Offset(
    Random().nextDouble() * 2 - 1,
    Random().nextDouble() * 2 - 1,
  );
  final cube = Cube()
    ..offset = randomOffset
    ..delta = randomDelta
    ..direction = randomDirection;
  cubes.add(cube);
  debugPrint('Cube added: $randomOffset');
  }

  @override
  void start(Duration time) {
  final size = MediaQuery.of(context).size;
  addCube(size);
  super.start(time);
  }

  @override
  void update(Duration time) {
  for (final cube in cubes) {
    cube.update(time, constraints.biggest);
  }
  }

  @override
  Widget paint(BuildContext context, BoxConstraints constraints) {
  return Scaffold(
    appBar: AppBar(
    title: const Text('Animation Example'),
    ),
    body: Stack(
    fit: StackFit.expand,
    children: [
      for (final cube in cubes)
      Positioned.fromRect(
        rect: cube.rect,
        child: CustomPaint(
        painter: InlinePainter(
          draw: (canvas, size) {
          final paint = Paint()
            ..color = cube.color
            ..style = PaintingStyle.fill
            ..strokeWidth = 2;
          final rect = Rect.fromLTWH(0, 0, size.width, size.height);
          canvas.drawRect(rect, paint);
          },
        ),
        ),
      ),
    ],
    ),
    floatingActionButton: FloatingActionButton.extended(
    onPressed: () => addCube(constraints.biggest),
    icon: const Icon(Icons.add),
    label: Text('Cubes: ${cubes.length}'),
    ),
  );
  }
}

class Cube {
  Color color = Colors.black;
  Offset offset = Offset.zero;
  Size size = const Size(100, 100);
  double delta = 10;
  Offset direction = const Offset(0.1, 0.4);
  Rect get rect => offset & size;

  void update(Duration time, Size size) {
  // Move cube and change direction if out of bounds
  offset = offset + direction * delta;

  // Top
  if (offset.dy < 0) {
    direction = Offset(direction.dx, 1);
  }
  // Bottom
  if (offset.dy > size.height) {
    direction = Offset(direction.dx, -1);
  }
  // Left
  if (offset.dx < 0) {
    direction = Offset(1, direction.dy);
  }
  // Right
  if (offset.dx > size.width) {
    direction = Offset(-1, direction.dy);
  }

  // Change color
  color = Color.fromARGB(
    255,
    (offset.dx * 255 / size.width).round(),
    (offset.dy * 255 / size.height).round(),
    0,
  );
  }
}

flutter_implicit_animations's People

Contributors

rodydavis avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.