我是颤音初学者。我想创建一个带有按钮(自定义按钮小部件)的8x2网格视图,当gridview中的按钮(自定义按钮小部件)退出视图时,它们失去了状态,我也尝试了SilverGrid.There,同样的proplem.Here也是我的代码片段。当我向下滚动并返回到SoundCard顶部时,所选择的SoundCard状态就失去了状态,我附上了示例图片这里。
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就像按钮.When,我滚动并返回到顶部,选择的状态SoundCard按钮失去了它所选的state.Can,有谁能帮我摆脱这个问题?
发布于 2020-11-23 10:25:37
为了确保状态在离开屏幕后仍然保持,向状态添加一个名为AutomaticKeepAliveClientMixin的混合元素,并重写wantKeepAlive getter:
class _IndexState extends State<Index> with AutomaticKeepAliveClientMixin
{
@override
bool get wantKeepAlive => true;
...
}发布于 2020-11-23 11:37:04
我通过在我的AutomaticKeepAliveClientMixin中添加SounCard来解决上述问题。简单地说,当我们开发我们的应用程序时,我们的设计通常有一个带有多选项卡或页面视图的主屏幕。我们面临的问题是,当我们更改页面时,上一页的状态将丢失。太不方便了。
采用以下方法求解。
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);”
https://stackoverflow.com/questions/64966389
复制相似问题