Flutter - 保留不可见的gridview子项
Posted
技术标签:
【中文标题】Flutter - 保留不可见的gridview子项【英文标题】:Flutter - keep gridview children that are not visible 【发布时间】:2021-11-25 05:46:04 【问题描述】:我正在构建一个学生选择视图,但是当我滚动网格视图时,数据会丢失
视频示例:https://drive.google.com/file/d/1oB3VQHSfZzZjANC8dNnd4p4TmTIePqBC/view?usp=sharing
我很喜欢使用 addAutomaticKeepAlives 和 addRepaintBoundaries 属性
class StudentCellGridView extends StatelessWidget
const StudentCellGridView(
Key? key,
this.crossAxisCount = 4,
) : super(key: key);
final int crossAxisCount;
@override
Widget build(BuildContext context)
return GridView.builder(
addAutomaticKeepAlives: false,
addRepaintBoundaries: false,
padding: EdgeInsets.only(bottom: defaultPadding),
itemCount: 30,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: crossAxisCount,
mainAxisSpacing: defaultPadding,
),
itemBuilder: (context, index) => StudentCell(),
);
class _StudentCellState extends State<StudentCell>
var color = Colors.grey;
@override
Widget build(BuildContext context)
return Stack(
children: [
TextButton(
style: ButtonStyle(
overlayColor: MaterialStateColor.resolveWith(
(states) => Colors.transparent),
),
onPressed: ()
setState(()
this.color =
this.color == Colors.grey ? Colors.green : Colors.grey;
);
,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: defaultPadding),
child: Column(
children: [
SizedBox(
height: 80,
child: ClipRRect(
borderRadius: BorderRadius.circular(8.0),
child: Image.asset("assets/images/Foto.png"),
),
),
Expanded(
child: Container(
child: Center(
child: Text(
"Child name",
maxLines: 3,
style: TextStyle(color: Colors.black),
overflow: TextOverflow.ellipsis,
),
),
),
),
],
),
)),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Container(
width: 20,
height: 20,
decoration: new BoxDecoration(
color: this.color,
shape: BoxShape.circle,
),
),
SizedBox(
width: defaultPadding,
)
],
),
],
);
即使名单很长,我怎样才能保留选定的学生
【问题讨论】:
【参考方案1】:首先你的 GridView.builder() 小部件应该有addAutomaticKeepAlives: true
。
然后像这样将AutomaticKeepAliveClientMixin
添加到您的_StudentCellState 小部件中:
class _StudentCellState extends State<StudentCell> with AutomaticKeepAliveClientMixin
var color = Colors.grey;
@override
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context)
super.build(context);
return Stack(
children: [
//the rest of your code
],
);
【讨论】:
以上是关于Flutter - 保留不可见的gridview子项的主要内容,如果未能解决你的问题,请参考以下文章