直接上代码

  1. import 'package:flutter/material.dart';
  2. const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
  3. void main() {
  4. runApp(MyApp());
  5. }
  6. class MyApp extends StatelessWidget {
  7. @override
  8. Widget build(BuildContext context) {
  9. return MaterialApp(
  10. theme: ThemeData.dark().copyWith(
  11. scaffoldBackgroundColor: darkBlue,
  12. ),
  13. debugShowCheckedModeBanner: false,
  14. home: MyWidget(),
  15. );
  16. }
  17. }
  18. class MyWidget extends StatelessWidget {
  19. // 定义滚动 key
  20. final scrollKey = GlobalKey();
  21. @override
  22. Widget build(BuildContext context) {
  23. return Scaffold(
  24. body: ListView.builder(
  25. itemBuilder: (context, index) {
  26. return Container(
  27. // 这里是关键,需要滚动的位置加 key 即可
  28. key:index==8?scrollKey:null,
  29. height: 40,
  30. color: Colors.blue.withOpacity(index % 10 / 10.0),
  31. alignment:Alignment.center,
  32. child: Text(
  33. 'Item:$index',
  34. style: Theme.of(context).textTheme.bodyText1,
  35. ),
  36. );
  37. },
  38. itemCount: 40,
  39. ),
  40. floatingActionButton: FloatingActionButton(
  41. child:const Icon(Icons.add),
  42. onPressed: () {
  43. // 执行滚动到指定的 Item
  44. Scrollable.ensureVisible(scrollKey.currentContext!);
  45. },
  46. ),
  47. );
  48. }
  49. }

参考