直接上代码
import 'package:flutter/material.dart';
const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: darkBlue,
),
debugShowCheckedModeBanner: false,
home: MyWidget(),
);
}
}
class MyWidget extends StatelessWidget {
// 定义滚动 key
final scrollKey = GlobalKey();
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemBuilder: (context, index) {
return Container(
// 这里是关键,需要滚动的位置加 key 即可
key:index==8?scrollKey:null,
height: 40,
color: Colors.blue.withOpacity(index % 10 / 10.0),
alignment:Alignment.center,
child: Text(
'Item:$index',
style: Theme.of(context).textTheme.bodyText1,
),
);
},
itemCount: 40,
),
floatingActionButton: FloatingActionButton(
child:const Icon(Icons.add),
onPressed: () {
// 执行滚动到指定的 Item
Scrollable.ensureVisible(scrollKey.currentContext!);
},
),
);
}
}
参考