spinning_square.dart 2.63 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6 7
// This example shows how to perform a simple animation using the underlying
// render tree.

8 9 10 11
import 'dart:math' as math;

import 'package:flutter/animation.dart';
import 'package:flutter/rendering.dart';
12 13 14 15 16
import 'package:flutter/scheduler.dart';

class NonStopVSync implements TickerProvider {
  const NonStopVSync();
  @override
17
  Ticker createTicker(TickerCallback onTick) => Ticker(onTick);
18
}
19 20

void main() {
21
  // We first create a render object that represents a green box.
22
  final RenderBox green = RenderDecoratedBox(
23
    decoration: const BoxDecoration(color: Color(0xFF00FF00)),
24
  );
25 26
  // Second, we wrap that green box in a render object that forces the green box
  // to have a specific size.
27
  final RenderBox square = RenderConstrainedBox(
28
    additionalConstraints: const BoxConstraints.tightFor(width: 200.0, height: 200.0),
29
    child: green,
30
  );
31 32 33 34
  // Third, we wrap the sized green square in a render object that applies rotation
  // transform before painting its child. Each frame of the animation, we'll
  // update the transform of this render object to cause the green square to
  // spin.
35 36
  final RenderTransform spin = RenderTransform(
    transform: Matrix4.identity(),
37
    alignment: Alignment.center,
38
    child: square,
39
  );
40
  // Finally, we center the spinning green square...
41
  final RenderBox root = RenderPositionedBox(
42
    child: spin,
43
  );
44
  // and attach it to the window.
45
  RenderingFlutterBinding(root: root);
46

47 48
  // To make the square spin, we use an animation that repeats every 1800
  // milliseconds.
49
  final AnimationController animation = AnimationController(
50 51
    duration: const Duration(milliseconds: 1800),
    vsync: const NonStopVSync(),
52
  )..repeat();
53
  // The animation will produce a value between 0.0 and 1.0 each frame, but we
54
  // want to rotate the square using a value between 0.0 and math.pi. To change
55
  // the range of the animation, we use a Tween.
56
  final Tween<double> tween = Tween<double>(begin: 0.0, end: math.pi);
57 58
  // We add a listener to the animation, which will be called every time the
  // animation ticks.
59
  animation.addListener(() {
60 61 62 63 64
    // This code runs every tick of the animation and sets a new transform on
    // the "spin" render object by evaluating the tween on the current value
    // of the animation. Setting this value will mark a number of dirty bits
    // inside the render tree, which cause the render tree to repaint with the
    // new transform value this frame.
65
    spin.transform = Matrix4.rotationZ(tween.evaluate(animation));
66 67
  });
}