我想创建一个小部件,其中图像显示在一行中。
图片宽度与设备宽度相同。
所以我创建了listview,它有图像小部件
但是有些图像比设备高度大,图像被裁剪。
我可以为我的flutter项目做些什么?
这就是我所尝试的。
ListView.builder(
shrinkWrap: true,
scrollDirection:
widget.options.isHorizontal! ? Axis.horizontal : Axis.vertical,
physics:
widget.options.isHorizontal! ? const PageScrollPhysics() : null,
itemCount: widget.items?.length,
itemBuilder: (BuildContext context, int index) {
return Image.memory(
widget.items![index],
width: widget.options.isHorizontal!
? null
: MediaQuery.of(context).size.width,
height: widget.options.isHorizontal!
? MediaQuery.of(context).size.height
: null,
fit:
widget.options.isHorizontal! ? BoxFit.contain : BoxFit.fitWidth,
);
},
)
- 你可以使用ConstrainedBox
- 这个例子的JumpTo部分还不完美,我希望你可以通过学习ScrollNotification来实现它。
import 'package:flutter/material.dart';
class MyWidget extends StatefulWidget {
const MyWidget({super.key});
@override
State<MyWidget> createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
late ScrollController _controller;
bool lock = false;
@override
void initState() {
_controller = ScrollController();
super.initState();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
var maxWidth = MediaQuery.of(context).size.width;
var maxHeight = MediaQuery.of(context).size.height;
return Scaffold(
body: NotificationListener<ScrollNotification>(
child: ListView.builder(
controller: _controller,
physics: ClampingScrollPhysics(),
itemCount: 20,
itemExtent: maxWidth,
itemBuilder: (context, index) {
return ConstrainedBox(
constraints:
BoxConstraints(maxWidth: maxWidth, maxHeight: maxHeight),
child: Image.network('https://picsum.photos/600'));
},
scrollDirection: Axis.horizontal,
),
onNotification: (ScrollNotification notification) {
if (notification is ScrollStartNotification) {
lock = false;
}
if (notification is ScrollEndNotification &&
!lock &&
_controller.position.isScrollingNotifier.value &&
_controller.position.hasPixels) {
lock = true;
var current = _controller.offset;
var diffIndex = (current / maxWidth).floor();
var isNext = ((current / maxWidth).toDouble() * 0.001) > 0.5;
var nexPosition = 0.0;
if (isNext) {
nexPosition = (diffIndex + 1) * maxWidth;
} else {
nexPosition = diffIndex * maxWidth;
}
_controller.removeListener(() {});
Future.delayed(Duration.zero, () {
// _controller.jumpTo(nexPosition);
_controller.animateTo(nexPosition,
duration: Duration(milliseconds: 400),
curve: Curves.fastOutSlowIn);
}).whenComplete(() => _controller.addListener(() {}));
}
return lock;
},
),
);
}
}