首页 > 解决方案 > 实例成员“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

标签: flutterdart

解决方案


显示错误是因为您试图在初始化变量中使用方法。这在飞镖中是不可接受的。为避免这种情况,您可以创建一个返回小部件列表的方法,然后您可以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(),
      ),
    );
  }
}


推荐阅读