Как получить движущийся текст в виджете с заданной шириной

Я создаю приложение для радио. Как и в Spotify, есть полоса с текущим названием и исполнителем, текст должен быть в одну строку и заданной ширины. Как я могу позволить тексту перемещаться справа налево и обратно?

При использовании самодельной анимации я хочу иметь фиксированную скорость движущегося текста, поэтому мне нужно время и ширина текстового виджета.

Есть ли пакет/встроенная опция для этого? Или я должен использовать самодельную анимацию? Если да, то как я могу получить ширину текстового виджета?

Контроллер и анимация:

    AnimationController(duration: Duration(seconds: 10), vsync: this);
    animation = Tween<double>(begin: 0, end: 1)
        .animate(CurvedAnimation(parent: _controller, curve: Curves.linear));
    animation.addListener(() {
      setState(() {});
    });
    _controller.repeat();

метод сборки

    double value =
        -300 * (animation.value <= 0.5 ? animation.value : 1 - animation.value);
    return Container(
      child: SizedBox(
        width: widget.width,
        height: 24,
        child: Transform.translate(
          offset: Offset(value, 0),
          child: widget.text,
        ),
      ),
    );

person Butzlabben    schedule 16.04.2019    source источник


Ответы (2)


Вы можете сделать что-то вроде этого:

import 'dart:async';

import 'package:flutter/material.dart';

class ScrollingText extends StatefulWidget {
  final String text;
  final TextStyle textStyle;
  final Axis scrollAxis;
  final double ratioOfBlankToScreen;

  ScrollingText({
    @required this.text,
    this.textStyle,
    this.scrollAxis: Axis.horizontal,
    this.ratioOfBlankToScreen: 0.25,
  }) : assert(text != null,);

  @override
  State<StatefulWidget> createState() {
    return ScrollingTextState();
  }
}

class ScrollingTextState extends State<ScrollingText>
    with SingleTickerProviderStateMixin {
  ScrollController scrollController;
  double screenWidth;
  double screenHeight;
  double position = 0.0;
  Timer timer;
  final double _moveDistance = 3.0;
  final int _timerRest = 100;
  GlobalKey _key = GlobalKey();

  @override
  void initState() {
    super.initState();
    scrollController = ScrollController();
    WidgetsBinding.instance.addPostFrameCallback((callback) {
      startTimer();
    });
  }

  void startTimer() {
    if (_key.currentContext != null) {
      double widgetWidth =
          _key.currentContext.findRenderObject().paintBounds.size.width;
      double widgetHeight =
          _key.currentContext.findRenderObject().paintBounds.size.height;

      timer = Timer.periodic(Duration(milliseconds: _timerRest), (timer) {
        double maxScrollExtent = scrollController.position.maxScrollExtent;
        double pixels = scrollController.position.pixels;
        if (pixels + _moveDistance >= maxScrollExtent) {
          if (widget.scrollAxis == Axis.horizontal) {
            position = (maxScrollExtent -
                        screenWidth * widget.ratioOfBlankToScreen +
                        widgetWidth) /
                    2 -
                widgetWidth +
                pixels -
                maxScrollExtent;
          } else {
            position = (maxScrollExtent -
                        screenHeight * widget.ratioOfBlankToScreen +
                        widgetHeight) /
                    2 -
                widgetHeight +
                pixels -
                maxScrollExtent;
          }
          scrollController.jumpTo(position);
        }
        position += _moveDistance;
        scrollController.animateTo(position,
            duration: Duration(milliseconds: _timerRest), curve: Curves.linear);
      });
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    screenWidth = MediaQuery.of(context).size.width;
    screenHeight = MediaQuery.of(context).size.height;
  }

  Widget getBothEndsChild() {
    if (widget.scrollAxis == Axis.vertical) {
      String newString = widget.text.split("").join("\n");
      return Center(
        child: Text(
          newString,
          style: widget.textStyle,
          textAlign: TextAlign.center,
        ),
      );
    }
    return Center(
        child: Text(
      widget.text,
      style: widget.textStyle,
    ));
  }

  Widget getCenterChild() {
    if (widget.scrollAxis == Axis.horizontal) {
      return Container(width: screenWidth * widget.ratioOfBlankToScreen);
    } else {
      return Container(height: screenHeight * widget.ratioOfBlankToScreen);
    }
  }

  @override
  void dispose() {
    super.dispose();
    if (timer != null) {
      timer.cancel();
    }
  }

  @override
  Widget build(BuildContext context) {
    return ListView(
      key: _key,
      scrollDirection: widget.scrollAxis,
      controller: scrollController,
      physics: NeverScrollableScrollPhysics(),
      children: <Widget>[
        getBothEndsChild(),
        getCenterChild(),
        getBothEndsChild(),
      ],
    );
  }
}

И используйте виджет следующим образом:

ScrollingText(
  text: text,
  textStyle: TextStyle(fontSize: 12),
)

введите описание изображения здесь

person divyanshu bhargava    schedule 16.04.2019
comment
Если вы используете Marquee (другой ответ) или этот ответ, не забудьте поместить его в контейнер и задать ему высоту и ширину, потому что Marque и приведенный выше пример listview - person Ray Rojas; 26.05.2021

используйте этот виджет из шапки pub.dev.

Marquee(
  text: 'There once was a boy who told this story about a boy: "',
)
person Taha Malik    schedule 15.12.2020