TextField调用控制器添加文本 文本区域自动滚动设置

595 阅读1分钟

我们在使用TextField时经常会使用TextField的控制器添加文本

但是这样有个问题,当添加的文本到达文本的最大行数后,再添加文本,文本区域不会自动滚动

这时我们需要手动调用TextField的滚动控制器scrollController跳转到区域底部

但这是有一个新问题,每次跳转TextField都会自动获取焦点,这时又会跳转到最上方,此时需要将焦点设置到最底部

以下是解决方案

setState(() {
  int a = Random().nextInt(2359866);
  textController.text += a.toString();
  textController.selection = TextSelection( // 设置光标到最末尾
      baseOffset: textController.text.length,
      extentOffset: textController.text.length);
  if (scrollController.hasClients)
    scrollController.animateTo(
      scrollController.position.maxScrollExtent, //滚动到底部
      duration: const Duration(milliseconds: 50),
      curve: Curves.easeOut,
    );
});