-
-
Notifications
You must be signed in to change notification settings - Fork 502
/
scroll_to_index_demo_page2.dart
112 lines (91 loc) · 2.6 KB
/
scroll_to_index_demo_page2.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
/// 滑动到指定位置 GlobalKey 版本
/// 基于 SingleChildScrollView 和 Column
class ScrollToIndexDemoPage2 extends StatefulWidget {
const ScrollToIndexDemoPage2({super.key});
@override
_ScrollToIndexDemoPageState2 createState() => _ScrollToIndexDemoPageState2();
}
class _ScrollToIndexDemoPageState2 extends State<ScrollToIndexDemoPage2> {
GlobalKey scrollKey = GlobalKey();
ScrollController controller = ScrollController();
List<ItemModel> dataList = [];
@override
void initState() {
dataList.clear();
for (int i = 0; i < 100; i++) {
dataList.add(ItemModel(i));
}
super.initState();
}
_scrollToIndex() {
var key = dataList[12];
///获取 renderBox
RenderBox renderBox =
key.globalKey.currentContext!.findRenderObject() as RenderBox;
///获取位置偏移,基于 ancestor: SingleChildScrollView 的 RenderObject()
double dy = renderBox
.localToGlobal(Offset.zero,
ancestor: scrollKey.currentContext!.findRenderObject())
.dy;
///计算真实位移
var offset = dy + controller.offset;
if (kDebugMode) {
print("*******$offset");
}
controller.animateTo(offset,
duration: const Duration(milliseconds: 500), curve: Curves.linear);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("ScrollToIndexDemoPage2"),
),
body: SingleChildScrollView(
key: scrollKey,
controller: controller,
child: Column(
children: dataList.map<Widget>((data) {
return CardItem(data, key: dataList[data.index].globalKey);
}).toList(),
),
),
persistentFooterButtons: <Widget>[
TextButton(
onPressed: () async {
_scrollToIndex();
},
child: const Text("Scroll to 12"),
),
],
);
}
}
class CardItem extends StatelessWidget {
final random = math.Random();
final ItemModel data;
CardItem(this.data, {super.key});
@override
Widget build(BuildContext context) {
return Card(
child: Container(
height: (300 * random.nextDouble()),
alignment: Alignment.centerLeft,
child: Container(
margin: const EdgeInsets.all(5),
child: Text("Item ${data.index}"),
),
),
);
}
}
class ItemModel {
///这个key是关键
GlobalKey globalKey = GlobalKey();
///可以添加你的代码
final int index;
ItemModel(this.index);
}