I need to access a Widget child's child from GestureDetector()

Hello everyone! I’m new to Flutter and Dart. I used the example project for physics animations found on the Flutter Docs to build my app. This is the example code:

import 'package:flutter/material.dart';
import 'package:flutter/physics.dart';

main() {
  runApp(MaterialApp(home: PhysicsCardDragDemo()));
}

class PhysicsCardDragDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: DraggableCard(
        child: FlutterLogo(
          size: 128,
        ),
      ),
    );
  }
}

/// A draggable card that moves back to [Alignment.center] when it's
/// released.
class DraggableCard extends StatefulWidget {
  final Widget child;
  DraggableCard({this.child});

  @override
  _DraggableCardState createState() => _DraggableCardState();
}

class _DraggableCardState extends State<DraggableCard>
    with SingleTickerProviderStateMixin {
  AnimationController _controller;

  /// The alignment of the card as it is dragged or being animated.
  ///
  /// While the card is being dragged, this value is set to the values computed
  /// in the GestureDetector onPanUpdate callback. If the animation is running,
  /// this value is set to the value of the [_animation].
  Alignment _dragAlignment = Alignment.center;

  Animation<Alignment> _animation;

  /// Calculates and runs a [SpringSimulation].
  void _runAnimation(Offset pixelsPerSecond, Size size) {
    _animation = _controller.drive(
      AlignmentTween(
        begin: _dragAlignment,
        end: Alignment.center,
      ),
    );
    // Calculate the velocity relative to the unit interval, [0,1],
    // used by the animation controller.
    final unitsPerSecondX = pixelsPerSecond.dx / size.width;
    final unitsPerSecondY = pixelsPerSecond.dy / size.height;
    final unitsPerSecond = Offset(unitsPerSecondX, unitsPerSecondY);
    final unitVelocity = unitsPerSecond.distance;

    const spring = SpringDescription(
      mass: 30,
      stiffness: 1,
      damping: 1,
    );

    final simulation = SpringSimulation(spring, 0, 1, -unitVelocity);

    _controller.animateWith(simulation);
  }

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(vsync: this);

    _controller.addListener(() {
      setState(() {
        _dragAlignment = _animation.value;
      });
    });
  }

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

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return GestureDetector(
      onPanDown: (details) {
        _controller.stop();
      },
      onPanUpdate: (details) {
        setState(() {
          _dragAlignment += Alignment(
            details.delta.dx / (size.width / 2),
            details.delta.dy / (size.height / 2),
          );
        });
      },
      onPanEnd: (details) {
        _runAnimation(details.velocity.pixelsPerSecond, size);
      },
      child: Align(
        alignment: _dragAlignment,
        child: Card(
          child: widget.child,
        ),
      ),
    );
  }
}

I wanted to animate other properties of the DraggableCard() besides its Alignment(); specifically I wanted to dinamically change its rotation based on the horizontal drag.
I did that by using _dragAlignment.x:

return GestureDetector(

  onPanDown: (details) {
    _controller.stop();
  },
  onPanUpdate: (details) {

    //print(_dragAlignment);
    setState(() {

      _dragAlignment += Alignment(

        details.delta.dx / (size.width / 300), // X drag sensitivity
        details.delta.dy / (size.height / 9), //Y drag sensitivity

      );
    });
  },
  onPanEnd: (details) {
    _runAnimation(details.velocity.pixelsPerSecond, size);
  },
  child: Align(
    alignment: _dragAlignment,
        child: Transform.rotate(

            angle: -_dragAlignment.x/200,
              child: Card(
                child: widget.child,
              ),
        )
  ),
);

Now I’m trying to animate the opacity of a child of the card.
I thought it was gonna be simple, my idea was just giving _dragAlignment.x to a Opacity() function. But obviously if I do that, the whole card changes its opacity when I drag horizontally, but I only need the card’s child to change opacity.

I’m not sure how to access the child.

Unlike the exemple code, my DraggableCard() looks like this:

class PhysicsCardDragDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: DraggableCard( //Active card

          child: Stack(
            children: [

              FlutterLogo(size: 128),
             Text('Fading text'),


         ]
        )
    ),
);

}
}

Both the Flutter Logo and the Text correctly drag and rotate, but I need to change only the Text’s opacity when I drag.

I solved it like this:

 child: Align( alignment: _dragAlignment, child: Transform.rotate(
             angle: -_dragAlignment.x/200,
               child: Stack(
                 children: [
                     widget.child,
                     Opacity(
                     opacity: valueLimit((_dragAlignment.x).abs() * 0.009, 0.0, 1.0),
                     child: Text('My text')
                     )
                     ]
               ),
         )
   ),
2 Likes

thanks for sharing the solution!