这也可以在无状态的小部件中完成,通过在构建方法中触发它。使用addPostFrameCallback
确保滚动是在渲染完成后执行的。您需要为选择的value
添加状态管理。但是你可以选择使用GetX、StatefulWidget或其他任何方式。
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatelessWidget {
MyHomePage({Key? key, this.title}) : super(key: key);
final String? title;
static final List<GlobalKey> _key = List.generate(20, (index) => GlobalKey());
final List<Widget> buttons = List.generate(
20,
(index) => ElevatedButton(
onPressed: () {},
style: ButtonStyle(backgroundColor: MaterialStateProperty.resolveWith((_)=> index % 2 == 0 ? Colors.lightGreen : Colors.orange)),
child: Text("Button No # ${index + 1}", key: _key[index]),
),
);
@override
Widget build(BuildContext context) {
final thisWidget = Scaffold(
appBar: AppBar(
title: Text(title!),
),
body: Column(
children: [
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: buttons,
),
),
DropdownButton(
value: 0,
items: List.generate(
20,
(index) => DropdownMenuItem(
value: index,
child: Text("Goto Button # ${index + 1}")),
),
onChanged: (value) {
if (value != null) {
WidgetsBinding.instance
.addPostFrameCallback((_) => Scrollable.ensureVisible(_key[value].currentContext!));
}
},
)
],
),
);
WidgetsBinding.instance
.addPostFrameCallback((_) => Scrollable.ensureVisible(_key[15].currentContext!));
return thisWidget;
}
}
Scrollable.ensureVisible
方法即可。 - pskink