dart – 如何使用Flutter创建可滚动的环绕视图?
发布时间:2020-12-14 14:50:36 所属栏目:百科 来源:网络整理
导读:我希望显示有限数量的项目,并在用户向任一方向滚动时进行换行.我该怎么做呢? 解决方法 使用无限长度的ListView.builder无法轻松解决这个问题,因为它只能向一个方向发展.如果要在两个方向上进行换行,可以使用两个相反方向的堆栈模拟双向换行. import 'packag
我希望显示有限数量的项目,并在用户向任一方向滚动时进行换行.我该怎么做呢?
解决方法
使用无限长度的ListView.builder无法轻松解决这个问题,因为它只能向一个方向发展.如果要在两个方向上进行换行,可以使用两个相反方向的堆栈模拟双向换行.
import 'package:flutter/material.dart'; void main() { runApp(new MaterialApp( home: new HomePage(),)); } class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text('Wrapping List View'),),body: new WrappingListView.builder( itemCount: 10,itemBuilder: (BuildContext context,int index) { return new Card( child: new Container( height: 50.0,color: Colors.blue.withOpacity(index / 10),child: new Center( child: new Text('Card $index') ),); },); } } class WrappingListView extends StatefulWidget { factory WrappingListView({ Key key,List<Widget> children }) { return new WrappingListView.builder( itemCount: children.length,int index) { return children[index % children.length]; },); } WrappingListView.builder({ Key key,this.itemBuilder,this.itemCount }) : super(key: key); final int itemCount; final IndexedWidgetBuilder itemBuilder; WrappingListViewState createState() => new WrappingListViewState(); } class UnboundedScrollPosition extends ScrollPositionWithSingleContext { UnboundedScrollPosition({ ScrollPhysics physics,ScrollContext context,ScrollPosition oldPosition,}) : super(physics: physics,context: context,oldPosition: oldPosition); @override double get minScrollExtent => double.negativeInfinity; } class UnboundedScrollController extends ScrollController { @override UnboundedScrollPosition createScrollPosition( ScrollPhysics physics,) { return new UnboundedScrollPosition( physics: physics,oldPosition: oldPosition,); } } class WrappingListViewState extends State<WrappingListView> { UnboundedScrollController _controller = new UnboundedScrollController(); UnboundedScrollController _negativeController = new UnboundedScrollController(); @override void initState() { _controller.addListener(() { _negativeController.jumpTo( -_negativeController.position.extentInside - _controller.position.pixels,); }); } @override Widget build(BuildContext context) { return new Stack( children: <Widget>[ new CustomScrollView( physics: new AlwaysScrollableScrollPhysics(),controller: _negativeController,reverse: true,slivers: <Widget>[ new SliverList( delegate: new SliverChildBuilderDelegate( (BuildContext context,int index) { return widget.itemBuilder( context,(widget.itemCount - 1 - index) % widget.itemCount,); } ),],new ListView.builder( controller: _controller,int index) { return widget.itemBuilder(context,index % widget.itemCount); },); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |