Я делаю приложение на Flutter. Я создал список для своего приложения и создал эффект прокрутки вправо в своем списке. Но когда я перемещаю элемент в списке вправо, все элементы в списке сдвигаются вправо. Точно так же, когда я перемещаю его влево, он смещается влево. Для этого есть готовые инструменты (flutter_slidable), но я хочу создать более конкретный элемент списка. Я также добавляю свои коды и текущую работу. Заранее спасибо, если у кого есть решение по данному вопросу.
введите здесь описание изображения
введите здесь описание изображения
import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
var horizontalDrag = 0.0;
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Column(
children: [
ListView.builder(
itemCount: 3,
shrinkWrap: true,
itemBuilder: (BuildContext context, int index) {
return Container(
height: 75,
width: 360,
child: Stack(
children: [
Positioned(
left: 10,
child: GestureDetector(
onTap: () {
print("index $index");
},
child: Container(
width: 80,
height: 50,
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(20)),
child: Align(
child: Padding(
child: Icon(Icons.add),
padding: EdgeInsets.only(left: 10),
),
alignment: Alignment.centerLeft,
),
),
),
),
GestureDetector(
onTap: () {
print("index $index");
},
child: AnimatedContainer(
duration: Duration(milliseconds: 200),
child: Listener(
onPointerMove: (value) {
setState(() {
if (value.delta.dx.isNegative == true) {
horizontalDrag = 0.0;
} else {
horizontalDrag = 50.0;
}
});
},
child: Container(
margin: EdgeInsets.only(left: horizontalDrag),
width: 200,
height: 50,
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(20)),
child: Center(
child: Text(
"Try $index",
style: TextStyle(
fontSize: 14, color: Colors.white),
),
),
),
)),
),
],
),
);
},
),
],
);
}
}
В вашем примере переменная, используемая для сохранения позиции перетаскивания, только одна, а List
содержит три элемента.
Решение состоит в том, чтобы использовать List
из double
, чтобы сохранить позицию перетаскивания каждого элемента:
List<double> horizontalDrag = [0, 0, 0];
Потребуется сохранить horizontalDrag
относительно каждого элемента в обратном вызове onPointerMove
:
onPointerMove: (value) {
setState(() {
if (value.delta.dx.isNegative == true) {
horizontalDrag[index] = 0.0;
} else {
horizontalDrag[index] = 50.0;
}
}
);
И отобразите элемент соответственно:
Container(
margin:
EdgeInsets.only(left: horizontalDrag[index]),
),
Это скриншот результата:
Следует полному рабочему примеру:
class _HomePageState extends State<HomePage> {
List<double> horizontalDrag = [0, 0, 0];
@override
Widget build(BuildContext context) {
return Column(
children: [
ListView.builder(
itemCount: 3,
shrinkWrap: true,
itemBuilder: (BuildContext context, int index) {
return Container(
height: 75,
width: 360,
child: Stack(
children: [
Positioned(
left: 10,
child: GestureDetector(
onTap: () {
print("index $index");
},
child: Container(
width: 80,
height: 50,
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(20)),
child: Align(
child: Padding(
child: Icon(Icons.add),
padding: EdgeInsets.only(left: 10),
),
alignment: Alignment.centerLeft,
),
),
),
),
GestureDetector(
onTap: () {
print("index $index");
},
child: AnimatedContainer(
duration: Duration(milliseconds: 200),
child: Listener(
onPointerMove: (value) {
setState(() {
if (value.delta.dx.isNegative == true) {
horizontalDrag[index] = 0.0;
} else {
horizontalDrag[index] = 50.0;
}
});
},
child: Container(
margin:
EdgeInsets.only(left: horizontalDrag[index]),
width: 200,
height: 50,
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(20)),
child: Center(
child: Text(
"Try $index",
style: TextStyle(
fontSize: 14, color: Colors.white),
),
),
),
)),
),
],
),
);
},
),
],
);
}
}
Рад был помочь! Не забудьте отметить ответ как правильный
Большое спасибо. Это было именно то, что я хотел. Я занимаюсь этой проблемой в течение 3 дней. Это было наконец решено.