flutter 文字从左到右轮播滚动,跑马灯

参考

/// description_begin.
/// 跑马灯, 根据滚动方向可以分为 横向滚动 和 纵向滚动。
/// 此页实现的跑马灯是 横向滚动的。
/// description_end.
import 'dart:async';
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  MyApp({Key? key}) : super(key: key) {
    debugPrint('Track_MyApp');
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('跑马灯'),
        ),
        //body占屏幕的大部分。
        body: _buildBody(),
      ),
    );
  }

  Widget _buildBody() {
    return Container(
        margin: const EdgeInsets.only(left: 15, top: 10, right: 15),
        padding: const EdgeInsets.only(left: 15, right: 15),
        height: 36,
        decoration: BoxDecoration(
          color: const Color(0xFFAAAAAA),
          borderRadius: BorderRadius.circular(15),
        ),
        child: Row(
          children: <Widget>[
            Container(
              margin: const EdgeInsets.only(right: 10),
              width: 15,
              height: 15,
              decoration: const BoxDecoration(
                color: Colors.blue,
              ),
            ),
            Expanded(
              child: MarqueeView(
                child: _buildText(
                    '手机用户155****0523借款成功 ( This text is to long to be shown in just one line. )'),
              ),
            ),
          ],
        ));
  }

  Widget _buildText(String txt) {
    return Text(
      txt,
      style: const TextStyle(
        fontSize: 13,
        color: Colors.white,
      ),
      maxLines: 1,
      overflow: TextOverflow.fade,
    );
  }
}

//

class MarqueeView extends StatefulWidget {
  final Duration pauseDuration, forwardDuration;
  final double scrollSpeed; //滚动速度(时间单位是秒)。
  final Widget child; //子视图。

  /// 注: 构造函数入参的默认值必须是常量。
  const MarqueeView(
      {Key? key,
      this.pauseDuration = const Duration(milliseconds: 100),
      this.forwardDuration = const Duration(milliseconds: 3000),
      this.scrollSpeed = 40.0,
      required this.child})
      : super(key: key);

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

class _MarqueeViewState extends State<MarqueeView>
    with SingleTickerProviderStateMixin {
  bool _validFlag = true;
  double _boxWidth = 0;
  final ScrollController _controller = ScrollController();

  @override
  void dispose() {
    debugPrint('Track_MarqueeView_dispose');
    _validFlag = false;
    _controller.dispose();
    super.dispose();
  }

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

  @override
  Widget build(BuildContext context) {
    /// 使用LayoutBuilder获取组件的大小。
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        _boxWidth = constraints.maxWidth;
        return SingleChildScrollView(
          // 禁止手动滑动。
          physics: const NeverScrollableScrollPhysics(),
          controller: _controller,
          scrollDirection: Axis.horizontal,
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: _boxWidth),
            child: widget.child,
          ),
        );
      },
    );
  }

  void scroll() async {
    while (_validFlag) {
      debugPrint('Track_MarqueeView_scroll');
      await Future.delayed(widget.pauseDuration);
      if (_boxWidth <= 0) {
        continue;
      }
      _controller.jumpTo(0);
      // 两个方向: Curves.easeIn 和 Curves.easeOut 。
      await _controller.animateTo(_controller.position.maxScrollExtent,
          duration: Duration(
              seconds:
                  (_controller.position.maxScrollExtent / widget.scrollSpeed)
                      .floor()),
          curve: Curves.easeIn);
    }
  }
}

我自己的跑马灯需要用到多语言,需要用到html

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

import '../widget/marquee_view.dart';

class DirectText extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => DirectTextState();
}

class DirectTextState extends State<DirectText> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('跑马灯'),
        ),
        //body占屏幕的大部分。
        body: _buildBody(),
      ),
    );
  }

  Widget _buildBody() {
    return Column(
      children: [
        Container(alignment: Alignment.centerLeft,child: htmlText()),
        Container(
            margin: const EdgeInsets.only(left: 15, top: 10, right: 15),
            padding: const EdgeInsets.only(left: 15, right: 15),
            height: 36,
            decoration: BoxDecoration(
              color: const Color(0xFFAAAAAA),
              borderRadius: BorderRadius.circular(15),
            ),
            child: Row(
              children: <Widget>[
                Container(
                  margin: const EdgeInsets.only(right: 10),
                  width: 15,
                  height: 15,
                  decoration: const BoxDecoration(
                    color: Colors.blue,
                  ),
                ),
                Expanded(
                  child: MarqueeView(
                    child: Row(
                      children: [
                        htmlText(),
                        htmlText(),
                        htmlText(),
                        htmlText(),
                        htmlText(),
                        htmlText(),
                      ],
                    ),
                  ),
                ),
              ],
            )),
      ],
    );
  }

  String textData = """
<p > This <b>num</b> is some text</p>
""";

  Widget htmlText() {
    return Container(
      color: Colors.blue,
      child: Html(shrinkWrap: true, data: textData, style: {
        "html": Style(
            padding: EdgeInsets.all(0),
            margin: EdgeInsets.all(0),
            backgroundColor: Colors.grey,
            textAlign: TextAlign.center),
        "body": Style(padding: EdgeInsets.all(0), margin: EdgeInsets.all(0)),
        "p": Style(
            padding: EdgeInsets.all(0),
            margin: EdgeInsets.all(0),
            fontSize: FontSize.rem(1.02),
            color: const Color(0xFF373737),
            fontWeight: FontWeight.w400),
        "p > b": Style(
            padding: EdgeInsets.all(0),
            margin: EdgeInsets.all(0),
            fontSize: FontSize.rem(1.02),
            color: const Color(0xFF373737),
            fontWeight: FontWeight.w600)
      }),
    );
  }
}


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

class MarqueeView extends StatefulWidget {
  final Duration pauseDuration, forwardDuration;
  final double scrollSpeed; //滚动速度(时间单位是秒)。
  final Widget child; //子视图。

  /// 注: 构造函数入参的默认值必须是常量。
  const MarqueeView(
      {Key? key,
        this.pauseDuration = const Duration(milliseconds: 100),
        this.forwardDuration = const Duration(milliseconds: 3000),
        this.scrollSpeed = 40.0,
        required this.child})
      : super(key: key);

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

class _MarqueeViewState extends State<MarqueeView>
    with SingleTickerProviderStateMixin {
  bool _validFlag = true;
  double _boxWidth = 0;
  final ScrollController _controller = ScrollController();

  @override
  void dispose() {
    debugPrint('Track_MarqueeView_dispose');
    _validFlag = false;
    _controller.dispose();
    super.dispose();
  }

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

  @override
  Widget build(BuildContext context) {
    /// 使用LayoutBuilder获取组件的大小。
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        _boxWidth = constraints.maxWidth;
        return SingleChildScrollView(
          // 禁止手动滑动。
          physics: const NeverScrollableScrollPhysics(),
          controller: _controller,
          scrollDirection: Axis.horizontal,
          child: Container(
            //两侧的边距
            padding: EdgeInsets.symmetric(horizontal: _boxWidth),
            child: widget.child,
          ),
        );
      },
    );
  }

  void scroll() async {
    while (_validFlag) {
      debugPrint('Track_MarqueeView_scroll');
      await Future.delayed(widget.pauseDuration);
      if (_boxWidth <= 0) {
        continue;
      }
      _controller.jumpTo(_boxWidth);
      // 两个方向: Curves.easeIn 和 Curves.easeOut 。
      await _controller.animateTo(_controller.position.maxScrollExtent,
          duration: Duration(
              seconds:
              (_controller.position.maxScrollExtent / widget.scrollSpeed)
                  .floor()),
          curve: Curves.easeOut);
    }
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值