源代码:
import 'package:flutter/material.dart';
main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title:'app标题' ,
home: HYHomePage(),
);
}
}
class HYHomePage extends StatefulWidget {
@override
_HYHomePageState createState() => _HYHomePageState();
}
class _HYHomePageState extends State<HYHomePage> {
ScrollController _controller;
bool _isShowTop=false;
@override
void initState() {
// TODO: implement initState
_controller=ScrollController();
_controller.addListener(() {
final tempOffSet=_controller.offset>=1000;
if(tempOffSet!=_isShowTop){
setState(() {
_isShowTop=tempOffSet;
});
}
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("标题"),
),
body: ListView.builder(
itemExtent: 50,
itemCount: 100,
controller: _controller,
itemBuilder: (ctx,index){
return ListTile(title: Text("第$index条,"),);
}
),
floatingActionButton: !_isShowTop ? null : FloatingActionButton(
child: Icon(Icons.arrow_upward),
onPressed: () {
_controller.animateTo(0, duration: Duration(milliseconds: 1000), curve: Curves.ease);
},
),
);
}
}
//思考:如果把BodyDemo抽离出来,此处是拿不到_controller的,应该怎么办?
//class BodyDemo extends StatelessWidget {
// @override
// Widget build(BuildContext context) {
// return ListView.builder(
// itemExtent: 50,
// itemCount: 100,
// controller: _controller,
// itemBuilder: (ctx,index){
// return ListTile(title: Text("第$index条,"),);
// }
// );
// }
//}
//class BodyDemo extends StatefulWidget {
// @override
// _BodyDemoState createState() => _BodyDemoState();
//}
//
//class _BodyDemoState extends State<BodyDemo> {
//
// @override
// Widget build(BuildContext context) {
// return ListView.builder(
// itemExtent: 50,
// itemCount: 100,
// controller: this._controller,
// itemBuilder: (ctx,index){
// return ListTile(title: Text("第$index条"),);
// }
// );
// }
//}
网友评论