opacity_peephole.dart 16.1 KB
Newer Older
1 2 3 4
// Copyright 2014 The Flutter 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
import 'dart:math';

7 8 9 10 11 12 13 14
import 'package:flutter/material.dart';

import '../common.dart';

// Various tests to verify that the Opacity layer propagates the opacity to various
// combinations of children that can apply it themselves.
// See https://github.com/flutter/flutter/issues/75697
class OpacityPeepholePage extends StatelessWidget {
15
  const OpacityPeepholePage({super.key});
16 17 18 19 20 21

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Opacity Peephole tests')),
      body: ListView(
22
        key: const Key(kOpacityScrollableName),
23 24 25 26 27 28 29 30
        children: <Widget>[
          for (OpacityPeepholeCase variant in allOpacityPeepholeCases)
            ElevatedButton(
              key: Key(variant.route),
              child: Text(variant.name),
              onPressed: () {
                Navigator.pushNamed(context, variant.route);
              },
31
            ),
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
        ],
      ),
    );
  }
}

typedef ValueBuilder = Widget Function(double v);
typedef AnimationBuilder = Widget Function(Animation<double> animation);

double _opacity(double v) => v * 0.5 + 0.25;
int _red(double v) => (v * 255).round();
int _green(double v) => _red(1 - v);
int _blue(double v) => 0;

class OpacityPeepholeCase {
  OpacityPeepholeCase.forValue({required String route, required String name, required ValueBuilder builder})
      : this.forAnimation(
    route: route,
    name: name,
    builder: (Animation<double> animation) => AnimatedBuilder(
      animation: animation,
      builder: (BuildContext context, Widget? child) => builder(animation.value),
    ),
  );

  OpacityPeepholeCase.forAnimation({required this.route, required this.name, required AnimationBuilder builder})
      : animationBuilder = builder;

  final String route;
  final String name;
  final AnimationBuilder animationBuilder;

  Widget buildPage(BuildContext context) {
    return VariantPage(variant: this);
  }
}

List<OpacityPeepholeCase> allOpacityPeepholeCases = <OpacityPeepholeCase>[
  // Tests that Opacity can hand down value to a simple child
  OpacityPeepholeCase.forValue(
    route: kOpacityPeepholeOneRectRouteName,
    name: 'One Big Rectangle',
    builder: (double v) {
      return Opacity(
        opacity: _opacity(v),
        child: Container(
          width: 300,
          height: 400,
          color: Color.fromARGB(255, _red(v), _green(v), _blue(v)),
        ),
      );
    }
  ),
  // Tests that a column of Opacity widgets can individually hand their values down to simple children
  OpacityPeepholeCase.forValue(
    route: kOpacityPeepholeColumnOfOpacityRouteName,
    name: 'Column of Opacity',
    builder: (double v) {
      return Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          for (int i = 0; i < 10; i++, v = 1 - v)
            Opacity(
              opacity: _opacity(v),
              child: Padding(
                padding: const EdgeInsets.all(5),
                child: Container(
                  width: 300,
                  height: 30,
                  color: Color.fromARGB(255, _red(v), _green(v), _blue(v)),
                ),
              ),
            ),
        ],
      );
    },
  ),
  // Tests that an Opacity can hand value down to a cached child
  OpacityPeepholeCase.forValue(
      route: kOpacityPeepholeOpacityOfCachedChildRouteName,
      name: 'Opacity of Cached Child',
      builder: (double v) {
        // ChildV starts as a constant so the same color pattern always appears and the child will be cached
        double childV = 0;
        return Opacity(
          opacity: _opacity(v),
          child: RepaintBoundary(
            child: SizedBox(
              width: 300,
              height: 400,
              child: Stack(
                children: <Widget>[
                  for (double i = 0; i < 100; i += 10, childV = 1 - childV)
                    Positioned.fromRelativeRect(
                      rect: RelativeRect.fromLTRB(i, i, i, i),
                      child: Container(
                        color: Color.fromARGB(255, _red(childV), _green(childV), _blue(childV)),
                      ),
                    ),
                ],
              ),
            ),
          ),
        );
      }
  ),
  // Tests that an Opacity can hand a value down to a Column of simple non-overlapping children
  OpacityPeepholeCase.forValue(
    route: kOpacityPeepholeOpacityOfColumnRouteName,
    name: 'Opacity of Column',
    builder: (double v) {
      return Opacity(
        opacity: _opacity(v),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            for (int i = 0; i < 10; i++, v = 1 - v)
              Padding(
                padding: const EdgeInsets.all(5),
                // RepaintBoundary here to avoid combining children into 1 big Picture
                child: RepaintBoundary(
                  child: Container(
                    width: 300,
                    height: 30,
                    color: Color.fromARGB(255, _red(v), _green(v), _blue(v)),
                  ),
                ),
              ),
          ],
        ),
      );
    },
  ),
  // Tests that an entire grid of Opacity objects can hand their values down to their simple children
  OpacityPeepholeCase.forValue(
    route: kOpacityPeepholeGridOfOpacityRouteName,
    name: 'Grid of Opacity',
    builder: (double v) {
      double rowV = v;
      double colV = rowV;
      return Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          for (int i = 0; i < 10; i++, rowV = 1 - rowV, colV = rowV)
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                for (int j = 0; j < 7; j++, colV = 1 - colV)
                  Opacity(
                    opacity: _opacity(colV),
                    child: Padding(
                      padding: const EdgeInsets.all(5),
                      child: Container(
                        width: 30,
                        height: 30,
                        color: Color.fromARGB(255, _red(colV), _green(colV), _blue(colV)),
                      ),
                    ),
                  ),
              ],
            ),
        ],
      );
    },
  ),
  // tests if an Opacity can hand its value down to a 2D grid of simple non-overlapping children.
  // The success of this case would depend on the sophistication of the non-overlapping tests.
  OpacityPeepholeCase.forValue(
    route: kOpacityPeepholeOpacityOfGridRouteName,
    name: 'Opacity of Grid',
    builder: (double v) {
      double rowV = v;
      double colV = rowV;
      return Opacity(
        opacity: _opacity(v),
        child: SizedBox(
          width: 300,
          height: 400,
          child: Stack(
            children: <Widget>[
              for (int i = 0; i < 10; i++, rowV = 1 - rowV, colV = rowV)
                for (int j = 0; j < 7; j++, colV = 1 - colV)
                  Positioned.fromRect(
                    rect: Rect.fromLTWH(j * 40 + 5, i * 40 + 5, 30, 30),
                    // RepaintBoundary here to avoid combining the 70 children into a single Picture
                    child: RepaintBoundary(
                      child: Container(
                        color: Color.fromARGB(255, _red(colV), _green(colV), _blue(colV)),
                      ),
                    ),
                  ),
            ],
          ),
        ),
      );
    },
  ),
  // tests if an Opacity can hand its value down to a Column of non-overlapping rows of non-overlapping simple children.
  // This test only requires linear non-overlapping tests to succeed.
  OpacityPeepholeCase.forValue(
    route: kOpacityPeepholeOpacityOfColOfRowsRouteName,
    name: 'Opacity of Column of Rows',
    builder: (double v) {
      double rowV = v;
      double colV = v;
      return Opacity(
        opacity: _opacity(v),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            for (int i = 0; i < 10; i++, rowV = 1 - rowV, colV = rowV)
              Padding(
                padding: const EdgeInsets.only(top: 5, bottom: 5),
                // RepaintBoundary here to separate each row into a separate layer child
                child: RepaintBoundary(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      for (int j = 0; j < 7; j++, colV = 1 - colV)
                        Padding(
                          padding: const EdgeInsets.only(left: 5, right: 5),
                          // RepaintBoundary here to prevent the row children combining into a single Picture
                          child: RepaintBoundary(
                            child: Container(
                              width: 30,
                              height: 30,
                              color: Color.fromARGB(255, _red(colV), _green(colV), _blue(colV)),
                            ),
                          ),
                        ),
                    ],
                  ),
                ),
              ),
          ],
        ),
      );
    },
  ),
  OpacityPeepholeCase.forAnimation(
    route: kOpacityPeepholeFadeTransitionTextRouteName,
    name: 'FadeTransition text',
    builder: (Animation<double> animation) {
      return FadeTransition(
        opacity: Tween<double>(begin: 0.25, end: 0.75).animate(animation),
        child: const SizedBox(
          width: 300,
          height: 400,
          child: Center(
            child: Text('Hello, World',
              style: TextStyle(fontSize: 48),
            ),
          ),
        ),
      );
    },
  ),
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
  OpacityPeepholeCase.forValue(
    route: kOpacityPeepholeGridOfRectsWithAlphaRouteName,
    name: 'Grid of Rectangles with alpha',
    builder: (double v) {
      return Opacity(
        opacity: _opacity(v),
        child: SizedBox.expand(
          child: CustomPaint(
            painter: RectGridPainter((Canvas canvas, Size size) {
              const int numRows = 10;
              const int numCols = 7;
              const double rectWidth = 30;
              const double rectHeight = 30;
              final double hGap = (size.width - numCols * rectWidth) / (numCols + 1);
              final double vGap = (size.height - numRows * rectHeight) / (numRows + 1);
              final double gap = min(hGap, vGap);
              final double xOffset = (size.width - (numCols * (rectWidth + gap) - gap)) * 0.5;
              final double yOffset = (size.height - (numRows * (rectHeight + gap) - gap)) * 0.5;
              final Paint rectPaint = Paint();
              for (int r = 0; r < numRows; r++, v = 1 - v) {
                final double y = yOffset + r * (rectHeight + gap);
                double cv = v;
                for (int c = 0; c < numCols; c++, cv = 1 - cv) {
                  final double x = xOffset + c * (rectWidth + gap);
                  rectPaint.color = Color.fromRGBO(_red(cv), _green(cv), _blue(cv), _opacity(cv));
                  final Rect rect = Rect.fromLTWH(x, y, rectWidth, rectHeight);
                  canvas.drawRect(rect, rectPaint);
                }
              }
            }),
          ),
        ),
      );
    },
  ),
  OpacityPeepholeCase.forValue(
    route: kOpacityPeepholeGridOfAlphaSaveLayerRectsRouteName,
    name: 'Grid of alpha SaveLayers of Rectangles',
    builder: (double v) {
      return Opacity(
        opacity: _opacity(v),
        child: SizedBox.expand(
          child: CustomPaint(
            painter: RectGridPainter((Canvas canvas, Size size) {
              const int numRows = 10;
              const int numCols = 7;
              const double rectWidth = 30;
              const double rectHeight = 30;
              final double hGap = (size.width - numCols * rectWidth) / (numCols + 1);
              final double vGap = (size.height - numRows * rectHeight) / (numRows + 1);
              final double gap = min(hGap, vGap);
              final double xOffset = (size.width - (numCols * (rectWidth + gap) - gap)) * 0.5;
              final double yOffset = (size.height - (numRows * (rectHeight + gap) - gap)) * 0.5;
              final Paint rectPaint = Paint();
              final Paint layerPaint = Paint();
              for (int r = 0; r < numRows; r++, v = 1 - v) {
                final double y = yOffset + r * (rectHeight + gap);
                double cv = v;
                for (int c = 0; c < numCols; c++, cv = 1 - cv) {
                  final double x = xOffset + c * (rectWidth + gap);
                  rectPaint.color = Color.fromRGBO(_red(cv), _green(cv), _blue(cv), 1.0);
                  layerPaint.color = Color.fromRGBO(255, 255, 255, _opacity(cv));
                  final Rect rect = Rect.fromLTWH(x, y, rectWidth, rectHeight);
                  canvas.saveLayer(null, layerPaint);
                  canvas.drawRect(rect, rectPaint);
                  canvas.restore();
                }
              }
            }),
          ),
        ),
      );
    },
  ),
  OpacityPeepholeCase.forValue(
    route: kOpacityPeepholeColumnOfAlphaSaveLayerRowsOfRectsRouteName,
    name: 'Grid with alpha SaveLayer on Rows',
    builder: (double v) {
      return Opacity(
        opacity: _opacity(v),
        child: SizedBox.expand(
          child: CustomPaint(
            painter: RectGridPainter((Canvas canvas, Size size) {
              const int numRows = 10;
              const int numCols = 7;
              const double rectWidth = 30;
              const double rectHeight = 30;
              final double hGap = (size.width - numCols * rectWidth) / (numCols + 1);
              final double vGap = (size.height - numRows * rectHeight) / (numRows + 1);
              final double gap = min(hGap, vGap);
              final double xOffset = (size.width - (numCols * (rectWidth + gap) - gap)) * 0.5;
              final double yOffset = (size.height - (numRows * (rectHeight + gap) - gap)) * 0.5;
              final Paint rectPaint = Paint();
              final Paint layerPaint = Paint();
              for (int r = 0; r < numRows; r++, v = 1 - v) {
                final double y = yOffset + r * (rectHeight + gap);
                layerPaint.color = Color.fromRGBO(255, 255, 255, _opacity(v));
                canvas.saveLayer(null, layerPaint);
                double cv = v;
                for (int c = 0; c < numCols; c++, cv = 1 - cv) {
                  final double x = xOffset + c * (rectWidth + gap);
                  rectPaint.color = Color.fromRGBO(_red(cv), _green(cv), _blue(cv), 1.0);
                  final Rect rect = Rect.fromLTWH(x, y, rectWidth, rectHeight);
                  canvas.drawRect(rect, rectPaint);
                }
                canvas.restore();
              }
            }),
          ),
        ),
      );
    },
  ),
402 403
];

404 405 406 407 408 409 410 411 412 413 414 415
class RectGridPainter extends CustomPainter {
  RectGridPainter(this.painter);

  final void Function(Canvas canvas, Size size) painter;

  @override
  void paint(Canvas canvas, Size size) => painter(canvas, size);

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}

416 417 418 419 420 421
Map<String, WidgetBuilder> opacityPeepholeRoutes = <String, WidgetBuilder>{
  for (OpacityPeepholeCase variant in allOpacityPeepholeCases)
    variant.route: variant.buildPage,
};

class VariantPage extends StatefulWidget {
422
  const VariantPage({super.key, required this.variant});
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459

  final OpacityPeepholeCase variant;

  @override
  State<VariantPage> createState() => VariantPageState();
}

class VariantPageState extends State<VariantPage> with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  @override
  void initState() {
    super.initState();

    _controller = AnimationController(vsync: this, duration: const Duration(seconds: 4));
    _controller.repeat(reverse: true);
  }

  @override
  void dispose() {
    _controller.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.variant.name),
      ),
      body: Center(
        child: widget.variant.animationBuilder(_controller),
      ),
    );
  }
}