【问题标题】:fadein fadeout repeatedly on multi-text in single widget在单个小部件中的多文本上反复淡入淡出
【发布时间】:2021-12-30 17:34:42
【问题描述】:

我是 Flutter 移动应用的新用户。如何使具有相同或单个小部件的多文本重复淡入淡出。就像下面的链接,https://www.radio5ive.com/。 我使用了AnimatedOpacity 小部件,但它不能正常工作。

// text show hide
  double opacity = 1.0;

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

  changeOpacity() {
    Future.delayed(Duration(seconds: 2), () {
      setState(() {
        opacity = opacity == 0.0 ? 1.0 : 0.0;
        changeOpacity();
      });
    });
  }

我正在使用它

   Container(
                child: AnimatedOpacity(
                  opacity: opacity,
                  duration: Duration(seconds: 2),
                  child: Container(
                    child: Text(
                      'Television contracts the imagination and radio expands it.',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        color: Colors.red,
                        fontSize: 30,
                      ),
                    ),
                  ),
                ),
              ),



//full code below
import 'dart:async';
import 'dart:ffi';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // const ({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

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

class _HomeScreenState extends State<HomeScreen> {
  AudioPlayer audioPlayer = new AudioPlayer();
  Duration duration = new Duration();
  Duration position = new Duration();
  bool playing = false;

  // disposing listener if not needed or users navigates away from
  @override
  void dispose() {
    super.dispose();
    audioPlayer.dispose();
  }

  // text show hide
  double opacity = 1.0;

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

  changeOpacity() {
    Future.delayed(Duration(seconds: 2), () {
      setState(() {
        opacity = opacity == 0.0 ? 1.0 : 0.0;
        changeOpacity();
      });
    });
  }
  // changeOpacity() {
  //   Timer.periodic(Duration(seconds: 2), (t) {
  //     setState(() {
  //       opacity = opacity == 0.0 ? 1.0 : 0.0;
  //       changeOpacity();
  //     });
  //   });
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        // color: Colors.white,
        backgroundColor: Color(0xff252525),
        appBar: AppBar(
          backgroundColor: Color(0xffffcb05),
          // title: Text('Radio5ive'),
          title: Image.asset(
            'assets/logoradio.png',
            fit: BoxFit.contain,
            height: 40,
            width: 40,
          ),

          actions: [IconButton(icon: Icon(Icons.search), onPressed: () {})],
          // flexibleSpace: Icon(Icons.camera),
          // flexibleSpace: SafeArea(
          //   child: Image(
          //     image: AssetImage('assets/logoradio.png'),
          //     height: 30,
          //     width: 30,
          //   ),
          // ),
        ),
        drawer: Drawer(
          elevation: 10.0,
          child: ListView(
            children: [
              UserAccountsDrawerHeader(
                accountName: Text('sundar'),
                accountEmail: Text('sundar@gmail.com'),
                currentAccountPicture: CircleAvatar(
                  backgroundColor: Colors.red,
                  child: Text('xyz'),
                ),
                otherAccountsPictures: [
                  CircleAvatar(
                    backgroundColor: Colors.red,
                    child: Text('ABC'),
                  )
                ],
              ),
              ListTile(
                title: Text('HOME'),
                leading: Icon(Icons.mail),
              ),
              Divider(
                height: 0.5,
                color: Colors.red,
              ),
              ListTile(
                title: Text('PODCAST'),
                leading: Icon(Icons.mail),
              ),
              Divider(
                height: 0.5,
                color: Colors.red,
              ),
              ListTile(
                title: Text('ABOUT'),
                leading: Icon(Icons.mail),
              ),
              Divider(
                height: 0.5,
                color: Colors.red,
              ),
              ListTile(
                title: Text('CONATACT'),
                leading: Icon(Icons.people),
              )
            ],
          ),
        ),
        body: SafeArea(
            child: Center(
          child: Column(
            children: [
              Container(
                child: AnimatedOpacity(
                  opacity: opacity,
                  duration: Duration(seconds: 2),
                  child: Container(
                    child: Text(
                      'Television contracts the imagination and radio expands it.',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        color: Colors.red,
                        fontSize: 30,
                      ),
                    ),
                  ),
                ),
              ),
              Container(
                child: AnimatedOpacity(
                  opacity: opacity == 1 ? 0 : 1,
                  duration: Duration(seconds: 1),
                  child: Container(
                    child: Text(
                      'Television contracts the imagination and radio expands it.',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        color: Colors.red,
                        fontSize: 30,
                      ),
                    ),
                  ),
                ),
              ),
              // Container(
              //   child: Image(
              //     image: AssetImage('assets/logoradio.png'),
              //     height: 100,
              //     width: 100,
              //   ),
              // ),
              // slider(),
              Container(
                  child: InkWell(
                onTap: () {
                  getAudio();
                },
                child: Icon(
                  playing == false
                      ? Icons.play_circle_outline
                      : Icons.pause_circle_outline,
                  size: 50,
                  color: Colors.red,
                ),
              )),
            ],
          ),
        )));
  }

  Widget slider() {
    return Slider.adaptive(
        min: 0.0,
        value: position.inSeconds.toDouble(),
        max: duration.inSeconds.toDouble(),
        onChanged: (double value) {
          setState(() {
            audioPlayer.seek(new Duration(seconds: value.toInt()));
          });
        });
  }

  void getAudio() async {
    var url = "https://live.radio5ive.com/proxy/radio5ivetamil/stream";
    // var url = "https://radio5ive.com/public/Neeye-Oli-MassTamilan.fm.mp3";
    // var url =
    //     "https://ia800905.us.archive.org/19/items/FREE_background_music_dhalius/backsound.mp3";
    // playing is false by default
    if (playing) {
      //pause song

      var res = await audioPlayer.pause();
      print('test');
      print(url);
      if (res == 1) {
        setState(() {
          playing = false;
        });
      }
    } else {
      //play song
      var res = await audioPlayer.play(url, isLocal: true);
      if (res == 1) {
        setState(() {
          playing = true;
        });
      }
    }
    audioPlayer.onAudioPositionChanged.listen((Duration dd) {
      setState(() {
        duration = dd;
      });
    });
    audioPlayer.onAudioPositionChanged.listen((Duration dd) {
      setState(() {
        position = dd;
      });
    });
  }
}

【问题讨论】:

    标签: flutter flutter-layout flutter-animation


    【解决方案1】:

    您正在使用 Future.delayed 意味着它将运行一次,在这种情况下您需要使用 Timer.periodic

    changeOpacity() {
        Timer.periodic(Duration(seconds: 2), (t) {
          setState(() {
            opacity = opacity == 0.0 ? 1.0 : 0.0;
          });
        });
      }
    

    延迟后开启动画需要 2 秒,而计时器是周期性的并且不等待动画结束,它是重叠的。


    更新 2multipleTextFade 翻译

    只需使用animated_text_kit

    SizedBox(
            width: 250.0,
            child: DefaultTextStyle(
              style: const TextStyle(
                fontSize: 32.0,
                fontWeight: FontWeight.bold,
              ),
              child: AnimatedTextKit(
                animatedTexts: [
                  FadeAnimatedText('do IT!'),
                  FadeAnimatedText('do it RIGHT!!'),
                  FadeAnimatedText('do it RIGHT NOW!!!'),
                ],
                onTap: () {
                  print("Tap Event");
                },
              ),
            ),
          ),
    

    更新单个动画

    要获得完美的动画,请使用FadeTransition

    class _MyStatefulWidgetState extends State<MyStatefulWidget>
        with TickerProviderStateMixin {
      late final AnimationController _controller = AnimationController(
        duration: const Duration(seconds: 2),
        vsync: this,
      )..repeat(reverse: true);
    
      late final Animation<double> _animation = CurvedAnimation(
        parent: _controller,
        curve: Curves.easeIn,
      );
    
      @override
      void dispose() {
        _controller.dispose();
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Column(
            children: [
              FadeTransition(
                opacity: _animation,
                child: const Padding(
                  padding: EdgeInsets.all(8),
                  child: Text(
                    'Television contracts the imagination and radio expands it.',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: Colors.red,
                      fontSize: 30,
                    ),
                  ),
                ),
              ),
              FadeTransition(
                key: ValueKey("animated 2"),
                opacity: _animation,
                child: const Padding(
                  padding: EdgeInsets.all(8),
                  child: Text(
                    'Television contracts the imagination and radio expands it.',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: Colors.red,
                      fontSize: 30,
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      }
    }
    
    

    更多关于

    【讨论】:

    • 我已经使用了以下代码,但在我的情况下它不起作用。 signle 小部件中的文本淡入淡出但使用此代码它卡在同一个地方没有淡入淡出。如果可能,提供工作演示。
    • 您是否使用stack 小部件作为其父小部件?
    • 出现拼写错误,已修复,检查更新,如果失败,能否包含完整的小部件?
    • 没有兄弟只使用了AnimatedOpacity
    • 您能否提供有关您的用例的更多详细信息,在我的情况下它运行良好,尝试flutter clean 并重建应用程序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多