GridView 中的项目在超出视口时会丢失其状态
Posted
技术标签:
【中文标题】GridView 中的项目在超出视口时会丢失其状态【英文标题】:Items in GridView lost its state when it when they are out of the viewport 【发布时间】:2021-03-06 01:09:52 【问题描述】:我是 Flutter 的初学者。我想用按钮(自定义按钮小部件)创建一个 8x2 网格视图。但是当 GridView 中的项目离开视口时,它们会丢失其状态。我也尝试过 SilverGrid。也有相同的问题。这是我的代码 sn-p .当我向下滚动并返回到 SoundCard 顶部时,SoundCard 的选定状态将丢失。我附上示例图片here。
import 'package:flutter/material.dart';
import 'package:relax/constants.dart';
import 'package:relax/soundcard.dart';
class Index extends StatefulWidget
@override
_IndexState createState() => _IndexState();
class _IndexState extends State<Index>
bool playState = false;
@override
Widget build(BuildContext context)
return Container(
color: Color(0xFF55b9f3),
child: GridView.count(
primary: false,
padding: const EdgeInsets.all(20),
crossAxisSpacing: 40,
mainAxisSpacing: 40,
crossAxisCount: 2,
children: <Widget>[
SoundCard(
assetName: 'rain',
),
SoundCard(
assetName: 'summernight',
),
SoundCard(
assetName: 'water',
),
SoundCard(
assetName: 'wind',
),
SoundCard(
assetName: 'thunderstorm',
),
SoundCard(
assetName: 'forest',
),
SoundCard(
assetName: 'leaves',
),
SoundCard(
assetName: 'fireplace',
),
SoundCard(
assetName: 'waterstream',
),
SoundCard(
assetName: 'seaside',
),
SoundCard(
assetName: 'brownnoise',
),
SoundCard(
assetName: 'coffeeshop',
),
SoundCard(
assetName: 'fan',
),
SoundCard(
assetName: 'pinknoise',
),
SoundCard(
assetName: 'whitenoise',
),
SoundCard(
assetName: 'train',
),
],
)
);
SoundCard 就像按钮。当我滚动并返回顶部时,SoundCard 按钮的选定状态将失去其选定状态。有人可以帮我解决这个问题吗?
【问题讨论】:
你能告诉我们代码,当你按下按钮时它被选中了吗? 谢谢!,我通过在我的声卡小部件中添加 `AutomaticKeepAliveClientMixin` 解决了这个问题 @ARUNBALAJI 请添加您的解决方案作为答案并接受它,以便有类似问题的人可以找到它。 【参考方案1】:为确保即使在离开屏幕后也能保持状态,请将名为 AutomaticKeepAliveClientMixin 的 mixin 添加到 State 并覆盖 wantKeepAlive getter:
class _IndexState extends State<Index> with AutomaticKeepAliveClientMixin
@override
bool get wantKeepAlive => true;
...
【讨论】:
【参考方案2】:我通过在我的 SounCard 中添加 AutomaticKeepAliveClientMixin
来解决上述问题。
简单来说
当我们开发我们的应用程序时,我们的设计通常有一个带有多标签栏或页面视图的主屏幕。我们遇到的问题是,当我们更改页面时,前一页的状态会丢失。很不方便。
通过以下方法解决。
class Page extends StatefulWidget
final String title;
const Page(
Key key,
@required this.title,
) : super(key: key);
@override
_PageState createState() => _PageState();
class _PageState extends State<Page> with AutomaticKeepAliveClientMixin
int _value = 0;
@override
Widget build(BuildContext context)
super.build(context); /// Remember to add this line!!!
...
...
@override
bool get wantKeepAlive => true;
记得加“super.build(context);”
【讨论】:
以上是关于GridView 中的项目在超出视口时会丢失其状态的主要内容,如果未能解决你的问题,请参考以下文章
Gridview 根据 Android 中的 SQLITE 状态高亮显示特定项目
SearchBar 处于活动状态时会超出 UINavigationItem 框架
gridview中的第一项在AdapterView.OnItemClickListener中不会更改