spinning_square.dart 2.47 KB
Newer Older
1 2 3 4
// Copyright 2016 The Chromium Authors. All rights reserved.
// 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 12 13
import 'dart:math' as math;

import 'package:flutter/animation.dart';
import 'package:flutter/rendering.dart';

void main() {
14
  // We first create a render object that represents a green box.
15 16 17
  RenderBox green = new RenderDecoratedBox(
    decoration: const BoxDecoration(backgroundColor: const Color(0xFF00FF00))
  );
18 19
  // Second, we wrap that green box in a render object that forces the green box
  // to have a specific size.
20 21 22 23
  RenderBox square = new RenderConstrainedBox(
    additionalConstraints: const BoxConstraints.tightFor(width: 200.0, height: 200.0),
    child: green
  );
24 25 26 27
  // 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.
28 29
  RenderTransform spin = new RenderTransform(
    transform: new Matrix4.identity(),
30
    alignment: FractionalOffset.center,
31 32
    child: square
  );
33
  // Finally, we center the spinning green square...
34
  RenderBox root = new RenderPositionedBox(
35
    alignment: FractionalOffset.center,
36 37
    child: spin
  );
38
  // and attach it to the window.
39 40
  new RenderingFlutterBinding(root: root);

41 42
  // To make the square spin, we use an animation that repeats every 1800
  // milliseconds.
43 44 45
  AnimationController animation = new AnimationController(
    duration: const Duration(milliseconds: 1800)
  )..repeat();
46 47 48
  // The animation will produce a value between 0.0 and 1.0 each frame, but we
  // want to rotate the square using a value between 0.0 and math.PI. To change
  // the range of the animation, we use a Tween.
49
  Tween<double> tween = new Tween<double>(begin: 0.0, end: math.PI);
50 51
  // We add a listener to the animation, which will be called every time the
  // animation ticks.
52
  animation.addListener(() {
53 54 55 56 57
    // 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.
58 59 60
    spin.transform = new Matrix4.rotationZ(tween.evaluate(animation));
  });
}