Флаттер условная анимация - PullRequest
       10

Флаттер условная анимация

0 голосов
/ 04 февраля 2019

У меня Stack из 5 Text, как дети.Каждый ребенок обернут предметом FadeTransition.Вне стека у меня есть 5 RaisedButton, который соответствует одному Text каждому.По умолчанию Text 1 имеет непрозрачность 1, а остальные имеют 0 непрозрачность.Когда кнопка нажата, непрозрачность текста, который она отображает, становится 1, а остальные становятся 0.Для этого я создал 5 различных AnimationController и жестко запрограммировал очень длинную логику. Я не уверен, что это правильный способ сделать это во Флаттере.Я считаю, что должен быть более простой способ. Более того, это упрощенный пример.Проблема в моем реальном приложении имеет даже сложные условия.(Например, показывать только текст 2 и текст 3, когда нажата кнопка 5, а логическое значение hasViewedText1 равно true.)

enter image description here

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

class Test extends StatefulWidget {
  @override
  _State createState() {
    return _State();
  }
}

class _State extends State<Test> with TickerProviderStateMixin {
  AnimationController _animationController1;
  AnimationController _animationController2;
  AnimationController _animationController3;
  AnimationController _animationController4;
  AnimationController _animationController5;

  @override
  void initState() {
    super.initState();
    _animationController1 = new AnimationController(
      vsync: this,
      duration: new Duration(seconds: 1),
    );
    _animationController2 = new AnimationController(
      vsync: this,
      duration: new Duration(seconds: 1),
    );
    _animationController3 = new AnimationController(
      vsync: this,
      duration: new Duration(seconds: 1),
    );
    _animationController4 = new AnimationController(
      vsync: this,
      duration: new Duration(seconds: 1),
    );
    _animationController5 = new AnimationController(
      vsync: this,
      duration: new Duration(seconds: 1),
    );
    _everyThingBackward();
    _animationController1.forward();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        elevation: 0.5,
        title: new Text(
          "Testing views",
          style: Theme.of(context).textTheme.title,
        ),
      ),
//      body: _buildBodyAnimationTest(),
//      body:  _buildTuto(),
//      body: _builtLayoutBuilder(),
      body: _builtLayoutConditionalAnimation(),
    );
  }


  Widget _builtLayoutConditionalAnimation() {
    return new Column(
      children: <Widget>[
        new Column(
          children: <Widget>[
            new RaisedButton(child: new Text("Button 1"), onPressed: () {
              _everyThingBackward();
              _animationController1.forward();
            }),
            new RaisedButton(child: new Text("Button 2"), onPressed: () {
              _everyThingBackward();
              _animationController2.forward();
            }),
            new RaisedButton(child: new Text("Button 3"), onPressed: () {
              _everyThingBackward();
              _animationController3.forward();
            }),
            new RaisedButton(child: new Text("Button 4"), onPressed: () {
              _everyThingBackward();
              _animationController4.forward();
            }),
            new RaisedButton(child: new Text("Button 5"), onPressed: () {
              _everyThingBackward();
              _animationController5.forward();
            }),
          ],
        ),
        new Stack(
          children: <Widget>[
            FadeTransition(opacity: _animationController1,child: new Text('Text 1 is clicked')),
            FadeTransition(opacity: _animationController2,child: new Text('Text 2 is clicked')),
            FadeTransition(opacity: _animationController3,child: new Text('Text 3 is clicked')),
            FadeTransition(opacity: _animationController4,child: new Text('Text 4 is clicked')),
            FadeTransition(opacity: _animationController5,child: new Text('Text 5 is clicked')),
          ],
        ),
      ],
    );
  }

  void _everyThingBackward() {
    _animationController1.reverse();
    _animationController2.reverse();
    _animationController3.reverse();
    _animationController4.reverse();
    _animationController5.reverse();

  }
}

1 Ответ

0 голосов
/ 04 февраля 2019

Это может сделать меня намного проще с помощью виджета AnimatedSwitcher, ссылки на документы .

Вот полный пример:

import 'package:flutter/material.dart';

void main() => runApp(App());

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(child: Center(child: Test())),
      ),
    );
  }
}

class Test extends StatefulWidget {
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {
  Widget _child = Text(
    "No Button Tapped!",
    key: UniqueKey(),
  );

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        RaisedButton(
          child: Text("Button 1"),
          onPressed: () {
            setState(() {
              _child = Text(
                "Button 1 Tapped!",
                key: UniqueKey(),
              );
            });
          },
        ),
        RaisedButton(
          child: Text("Button 2"),
          onPressed: () {
            setState(() {
              _child = Text(
                "Button 2 Tapped!",
                key: UniqueKey(),
              );
            });
          },
        ),
        RaisedButton(
          child: Text("Button 3"),
          onPressed: () {
            setState(() {
              _child = Text(
                "Button 3 Tapped!",
                key: UniqueKey(),
              );
            });
          },
        ),
        AnimatedSwitcher(
          duration: Duration(milliseconds: 200),
          child: _child,
        ),
      ],
    );
  }
}

Этосредняя статья тоже может быть полезна: https://medium.com/flutter-community/what-do-you-know-about-aniamtedswitcher-53cc3a4bebb8

...