Flutter BottomNavigationBar 二次点击 tab 时如何控制对应的列表页面回到顶部?
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Home(),
);
}
}
class Home extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _HomeState();
}
}
class _HomeState extends State<Home> {
static ScrollController scrollController = new ScrollController();
int _currentIndex = 0;
final List<Widget> _children = [
ListPage(),
BlankPage(),
BlankPage()
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Hello'),
),
body: _children[_currentIndex], // 当_currentIndex不变时,它时不会重绘页面的!
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
onTap: onTabTapped, // new
currentIndex: _currentIndex, // new
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Home'),
),
BottomNavigationBarItem(
icon: Icon(Icons.search),
title: Text('Search'),
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
title: Text('Me')
)
],
),
);
}
void onTabTapped(int index) {
setState(() {
if (_currentIndex == index) {
//how to controll the scrollConroller of ListPage?
}
_currentIndex = index;
});
}
}
class ListPage extends StatefulWidget{
@override
State<ListPage> createState() {
return ListPageState();
}
}
class ListPageState extends State<ListPage> {
ScrollController _scrollController = new ScrollController();
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
Container(
child: ListView.builder(
itemCount: 100,
itemBuilder: (BuildContext context, int index){
return Text("$index");
},
controller: _scrollController,
),
),
Positioned(
right: 15,
bottom: 15,
child: FloatingActionButton( //ListPage页内的控件可以控制_scrollController
child: Icon(Icons.arrow_upward),
onPressed: () {
_scrollController.animateTo(0.0, duration: Duration(milliseconds: 300), curve: Curves.easeOut);
},
),
)
],
);
}
}
class BlankPage extends StatelessWidget{
@override
Widget build(BuildContext context) {
return Center(
child: Text("Hello"),
);
}
}