Flutter简单的选取框小部件并使ScrollController未附加到任何滚动视图错误

时间:2019-12-30 07:30:24

标签: flutter

下面的这个简单小部件在我的应用程序中用于将简单的字幕文本制作成Text的另一个小部件,因为当文本长度太短时,我会收到此错误:

ScrollController not attached to any scroll views error

我的问题是知道如何动态计算文本长度并避免引发此错误?

例如:

MarqueeWidget(
  direction: Axis.horizontal,
  child: Text(
      '$parsedString', //-> text length is not known
    style: AppTheme.of(context).caption(
  ),
),

这是我从中使用的MarqueeWidget

class MarqueeWidget extends StatefulWidget {
  final Widget child;
  final Axis direction;
  final Duration animationDuration, backDuration, pauseDuration;

  MarqueeWidget({
    @required this.child,
    this.direction: Axis.horizontal,
    this.animationDuration: const Duration(milliseconds: 7000),
    this.backDuration: const Duration(milliseconds: 2000),
    this.pauseDuration: const Duration(milliseconds: 2000),
  });

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

class _MarqueeWidgetState extends State<MarqueeWidget> {
  ScrollController scrollController = ScrollController();

  @override
  void initState() {
    try{
      scroll();
    }catch(error){

    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: widget.child,
      scrollDirection: widget.direction,
      controller: scrollController,
    );
  }

  void scroll() async {
    while (true) {
      await Future.delayed(widget.pauseDuration);
      await scrollController.animateTo(
          scrollController.position.maxScrollExtent,
          duration: widget.animationDuration,
          curve: Curves.easeIn);
      await Future.delayed(widget.pauseDuration);
      await scrollController.animateTo(0.0,
          duration: widget.backDuration, curve: Curves.easeOut);
    }
  }
}

1 个答案:

答案 0 :(得分:0)

只需按照以下步骤更改代码,

    @override
      void initState() {
           WidgetsBinding.instance.addPostFrameCallback((_) {
           try {
               scroll();
           } catch (error){
               // log error
           }
    });
}
  一旦构建()方法呈现后,

WidgetsBinding.instance.addPostFrameCallback()方法就会被调用。

您遇到的错误是您正在调用scroll()方法,该方法尝试使用scrollController进行滚动,而scrollController可能在执行build方法之前被调用。