flutter - 实例成员“gantiIndex”不能作为初始化程序访问
问题描述
所以我正在尝试制作一个可滚动的按钮(inkwell)滚动视图,如果我按下按钮,它将突出显示我按下的按钮,并根据当前突出显示的按钮显示不同的信息。我决定使用 setState 来更改索引,但出现了这个问题标题中的错误。我尝试制作一个单独的函数以在 onTap 参数上使用,但它显示的是 gantiIndex 而不是 setState。谁能帮我解决这个问题?
这是代码:
class _BiodataGuruState extends State<BiodataGuru> {
int indexBiodata = 0;
void gantiIndex(int index) {
setState(() {
indexBiodata = index;
});
}
List _jenisBiodata = [
Container(
height: 30,
width: 172,
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Color.fromRGBO(51, 51, 51, 1),
),
),
),
child: InkWell(
onTap: () {
gantiIndex(0);
},
child: Text(
'Riwayat Pendidikan',
style: TextStyle(
fontFamily: 'Segoe UI',
fontSize: 18,
fontWeight: FontWeight.w600,
color: Color.fromRGBO(51, 51, 51, 1),
letterSpacing: 1,
),
),
),
),
这是错误消息:
The instance member 'gantiIndex' can't be accessed in an initializer.
Try replacing the reference to the instance member with a different expression
解决方案
显示错误是因为您试图在初始化变量中使用方法。这在飞镖中是不可接受的。为避免这种情况,您可以创建一个返回小部件列表的方法,然后您可以gantiIndex
在其中使用方法。看看下面的代码。
class _BiodataGuruState extends State<BiodataGuru> {
int indexBiodata = 0;
void gantiIndex(int index) {
setState(() {
indexBiodata = index;
});
}
List<Widget> _jenisBiodata() {
return [
Container(
height: 30,
width: 172,
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Color.fromRGBO(51, 51, 51, 1),
),
),
),
child: InkWell(
onTap: () {
gantiIndex(0);
},
child: Text(
'Riwayat Pendidikan',
style: TextStyle(
fontFamily: 'Segoe UI',
fontSize: 18,
fontWeight: FontWeight.w600,
color: Color.fromRGBO(51, 51, 51, 1),
letterSpacing: 1,
),
),
),
),
];
}
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: _jenisBiodata(),
),
);
}
}
推荐阅读
- embedded-jetty - Embedded Jetty 无法获取我的资源文件
- ruby-on-rails - 如何管理 Graylog 以正确解析我的 JSON 日志?
- php - 为什么这个 foreach 循环迭代两次?
- docker - 如何更新码头夏令时时间表
- python - 错误:inspector_emulator_agent.cc(477) 在通过 Selenium 和 ChromeDriver 执行测试时,只能为页面启用虚拟时间,而不是工作人员
- regex - 忽略 RegEx 中的不可见字符
- c# - 如何使部分方法异步
- python - 在 django 中同时更新模型并创建 pdf
- python - 在 pandas 中创建公司周数和年份
- istio - Istio helm 配置 - istio-ingressgateway 端口配置不起作用(或有意义)