android 如何只滚动到特定位置一次|Flutter

1dkrff03  于 2023-06-20  发布在  Android
关注(0)|答案(1)|浏览(165)

我试图使搜索应用程序更舒适时,用户点击搜索框滚动页面较低,因为键盘覆盖列表。首先点击搜索框向下滚动页面,但如果点击它可以再次滚动。Page
when i tapwhen i tap again
下面是我的代码:

  1. `class _SearchBox extends StatelessWidget {
  2. final Function()? onReset;
  3. final TextEditingController? controller;
  4. final ScrollController? scrollController;
  5. final FocusNode? focusNode;
  6. const _SearchBox({
  7. Key? key,
  8. this.onReset,
  9. this.controller,
  10. this.scrollController,
  11. this.focusNode,
  12. }) : super(key: key);
  13. @override
  14. Widget build(BuildContext context) {
  15. final InputBorder border =
  16. OutlineInputBorder(borderSide: BorderSide(color: Colors.grey[300]!));
  17. return TextField(
  18. focusNode: focusNode,
  19. onTap: () {
  20. scrollController?.animateTo(10 * 1000,
  21. duration: const Duration(milliseconds: 1000),
  22. curve: Curves.bounceIn);
  23. },
  24. autofocus: true,
  25. controller: controller,`

我尝试使用focunNode,但没有得到结果。我想滚动工作只工作一次,提前谢谢你!

2ledvvac

2ledvvac1#

我不完全明白问题出在哪里,但我已经想出了一个解决办法。您可以根据需要集成此代码。
demo gif

  1. final ScrollController _scrollController = ScrollController();
  2. final double textfieldHeight = 80;
  3. final double itemHeight = 100;
  4. void _scrollToIndex(int index) {
  5. _scrollController.animateTo(
  6. index * itemHeight + textfieldHeight,
  7. duration: Duration(milliseconds: 500),
  8. curve: Curves.ease,
  9. );
  10. }
  11. // index is a value that represents the position of the TextField in your list
  12. // itemHeight is a value that represents the height of each item in your list
  13. // note, if the TextField has focus, scrolling to the indices below the TextField will not occur.
  14. @override
  15. Widget build(BuildContext context) {
  16. return MaterialApp(
  17. title: 'Material App',
  18. home: Scaffold(
  19. appBar: AppBar(
  20. title: const Text('Material App Bar'),
  21. ),
  22. body: Padding(
  23. padding: const EdgeInsets.all(8.0),
  24. child: ListView(
  25. controller: _scrollController,
  26. children: [
  27. dummyWidget(),
  28. dummyWidget(),
  29. dummyWidget(),
  30. dummyWidget(),
  31. dummyWidget(),
  32. TextField(
  33. autofocus: false,
  34. decoration: InputDecoration(
  35. hintText: "TextField",
  36. border: OutlineInputBorder()
  37. ),
  38. onTap: () => _scrollToIndex(5)
  39. ),
  40. dummyWidget(),
  41. dummyWidget(),
  42. dummyWidget(),
  43. dummyWidget(),
  44. dummyWidget(),
  45. dummyWidget(),
  46. dummyWidget(),
  47. dummyWidget(),
  48. dummyWidget(),
  49. dummyWidget(),
  50. ],
  51. ),
  52. ),
  53. ),
  54. );
  55. }
  56. Container dummyWidget() {
  57. return Container(
  58. height: itemHeight,
  59. color: Colors.amber,
  60. margin: EdgeInsets.all(8),
  61. );
  62. }
展开查看全部

相关问题