【问题标题】:The instance member 'gantiIndex' can't be accessed as an initializer实例成员“gantiIndex”不能作为初始化程序访问
【发布时间】:2021-06-18 13:34:51
【问题描述】:

所以我正在尝试制作一个可滚动的按钮(墨水池)滚动视图,如果我按下该按钮,它将突出显示我按下的按钮,并根据当前突出显示的按钮显示不同的信息。我决定使用 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

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

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

    【讨论】:

    • 非常感谢 Alphamerc 先生。我真的很感激这个答案,它也很完美。希望你有一个美好的一天,并在你的工作中取得成功:D
    猜你喜欢
    • 2020-12-12
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 2022-01-15
    相关资源
    最近更新 更多