Flutter开发 SingleChildScrollView、ScrollController
SingleChildScrollView
滑动组件
有多张图片,左右滑动
class MyState extends State {bool flag = false; Widget build(BuildContext context) {double width = MediaQuery.of(context).size.width;double height = MediaQuery.of(context).size.height / 3;SingleChildScrollView singleChildScrollView = SingleChildScrollView(scrollDirection: Axis.horizontal,child: Row(children: [Image.network("https://pic.rmb.bdstatic.com/bjh/other/d1913ba5338a6ae4571a3d8e4ce469bf.png?for=bg",width: width,height: height,fit: BoxFit.cover,),Image.network("https://pic.rmb.bdstatic.com/bjh/3eacb728ac/240814/0c5c4e7a79d45ef72c1f934e9ed7edc6.jpeg",width: width,height: height,fit: BoxFit.cover,),Image.network("https://pic.rmb.bdstatic.com/bjh/other/d1913ba5338a6ae4571a3d8e4ce469bf.png?for=bg",width: width,height: height,fit: BoxFit.cover,),Image.network("https://pic.rmb.bdstatic.com/bjh/other/d1913ba5338a6ae4571a3d8e4ce469bf.png?for=bg",width: width,height: height,fit: BoxFit.cover,),],),);return Scaffold(appBar: AppBar(title: Text("SwitchListTile"), centerTitle: true),body: singleChildScrollView,);}
}
ScrollController
控制滑动
属性 | 说明 |
---|---|
initialScrollOffset | 设置滚动视图的初始位置 |
keepScrollOffset | 设置是否保存滚动位置 |
offset | 返回当前滚动位置的偏移量 |
jumpTo | 设置滚动到指定位置 |
animateTo | 设置带动画滚动到指定位置 |
在上面的例子中,添加按钮,用来滑动图片,只设置一个按钮。
class MyState extends State {bool flag = false; Widget build(BuildContext context) {double width = MediaQuery.of(context).size.width;double height = MediaQuery.of(context).size.height / 3;ScrollController scrollController = ScrollController();SingleChildScrollView singleChildScrollView = SingleChildScrollView(controller: scrollController,scrollDirection: Axis.horizontal,child: Row(children: [Image.network("https://pic.rmb.bdstatic.com/bjh/other/d1913ba5338a6ae4571a3d8e4ce469bf.png?for=bg",width: width,height: height,fit: BoxFit.cover,),Image.network("https://pic.rmb.bdstatic.com/bjh/3eacb728ac/240814/0c5c4e7a79d45ef72c1f934e9ed7edc6.jpeg",width: width,height: height,fit: BoxFit.cover,),Image.network("https://pic.rmb.bdstatic.com/bjh/other/d1913ba5338a6ae4571a3d8e4ce469bf.png?for=bg",width: width,height: height,fit: BoxFit.cover,),Image.network("https://pic.rmb.bdstatic.com/bjh/other/d1913ba5338a6ae4571a3d8e4ce469bf.png?for=bg",width: width,height: height,fit: BoxFit.cover,),],),);Stack stack = Stack(alignment: Alignment.centerRight,children: [singleChildScrollView,IconButton(onPressed: () {var old = scrollController.offset;scrollController.jumpTo(old +width);}, icon: Icon(Icons.navigate_next))],);return Scaffold(appBar: AppBar(title: Text(""), centerTitle: true),body: stack,);}
}