Flutter GridView中的项目在离开视口时会丢失其状态
我是颤振初学者。我想创建一个带有按钮的8x2 gridview(自定义按钮小部件)。但是gridview中的项目在离开视口时会失去其状态。我也尝试了SilverGrid。还有同样的问题。这是我的代码片段。当我向下滚动并返回声卡顶部时,声卡的选定状态将丢失。我附上了示例图片Flutter GridView中的项目在离开视口时会丢失其状态,flutter,gridview,widget,flutter-layout,flutter-animation,Flutter,Gridview,Widget,Flutter Layout,Flutter Animation,我是颤振初学者。我想创建一个带有按钮的8x2 gridview(自定义按钮小部件)。但是gridview中的项目在离开视口时会失去其状态。我也尝试了SilverGrid。还有同样的问题。这是我的代码片段。当我向下滚动并返回声卡顶部时,声卡的选定状态将丢失。我附上了示例图片 导入“包装:颤振/材料.省道”; 导入“package:relax/constants.dart”; 导入“package:relax/soundcard.dart”; 类索引扩展了StatefulWidget{ @凌驾 _I
导入“包装:颤振/材料.省道”;
导入“package:relax/constants.dart”;
导入“package:relax/soundcard.dart”;
类索引扩展了StatefulWidget{
@凌驾
_IndexState createState()=>U IndexState();
}
类_IndexState扩展状态{
bool playState=false;
@凌驾
小部件构建(构建上下文){
返回容器(
颜色:颜色(0xFF55b9f3),
子项:GridView.count(
主要:错误,
填充:常数边集。全部(20),
横轴间距:40,
平均间距:40,
交叉轴计数:2,
儿童:[
声卡(
资产名称:'雨',
),
声卡(
资产名称:“夏夜”,
),
声卡(
资产名称:“水”,
),
声卡(
资产名称:“风”,
),
声卡(
资产名称:“雷雨”,
),
声卡(
资产名称:“森林”,
),
声卡(
资产名称:'离开',
),
声卡(
资产名称:“壁炉”,
),
声卡(
资产名称:“waterstream”,
),
声卡(
资产名称:'海滨',
),
声卡(
资产名称:'brownnoise',
),
声卡(
资产名称:“咖啡店”,
),
声卡(
资产名称:'风扇',
),
声卡(
资产名称:“pinknoise”,
),
声卡(
资产名称:“白噪音”,
),
声卡(
资产名称:'列车',
),
],
)
);
}
}
声卡就像按钮一样。当我滚动并返回顶部时,声卡按钮的选定状态将丢失其选定状态。有人能帮我解决这个问题吗?要确保即使在离开屏幕导航后仍保持该状态,将名为automatickepaliveclientmixin的mixin添加到状态,并覆盖wantKeepAlivegetter,如下所示:
class _IndexState extends State<Index> with AutomaticKeepAliveClientMixin
{
@override
bool get wantKeepAlive => true;
...
}
class\u IndexState使用AutomaticEpaLiveClientMixin扩展状态
{
@凌驾
bool get wantKeepAlive=>true;
...
}
我通过在SounCard中添加AutomaticEpaLiveClientMixin
来解决上述问题。
简言之
当我们开发应用程序时,我们的设计通常有一个带有多选项卡栏或页面视图的主屏幕。问题是,当我们更改页面时,上一页的状态将丢失。这很不方便
用下面的方法求解
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;
}
类页面扩展StatefulWidget{
最后的字符串标题;
常数页({
关键点,
@需要这个标题,
}):super(key:key);
@凌驾
_PageState createState();
}
类_PageState使用AutomaticEpaLiveClientMixin扩展状态{
int _值=0;
@凌驾
小部件构建(构建上下文){
super.build(context);///记住添加这一行!!!
...
...
@凌驾
bool get wantKeepAlive=>true;
}
记得添加“super.build(context);”你能给我们看一下代码吗,当你按下按钮时,它被选中了?谢谢!我通过在声卡中添加“AutomaticEpaLiveClientMixin”解决了这个问题Widget@ARUNBALAJI请添加您的解决方案作为答案,并接受它,以便有类似问题的人可以找到它。
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;
}