如何通过颤振中的方法输入 update/setState bool 值?

How to update/setState bool value through a method's input in flutter?

这个问题可能有一个非常简单的答案,但我在尝试解决这个问题时受阻了一段时间,无法真正让它发挥作用。

**问题:**当我使用 initState 上的输入 got1Beans 调用 checkBeans() 时,我仍然得到 got1Beans 的初始值 (false)。我需要的是能够更新 got1Beans = true。任何人都能够解决这个问题?我在这里错过了什么?

import 'package:flutter/material.dart';

class BeansExample extends StatefulWidget {
 @override
_BeansExampleState createState() => _BeansExampleState();
}

class _BeansExampleState extends State<BeansExample> {
 bool got1beans = false;
 bool got2beans = false;
 bool got3beans = false;
 bool got4beans = false;
 bool got5beans = false;


checkBeans(bool getBeans) {
setState(() {
  getBeans = true;           //shouldn't it update the input value???
});
}



 @override
 void initState() {
  super.initState();
  checkBeans(got1beans);   //here I call got1Beans
  print(got1beans);        //This prints false, need to get true here 

    }

  @override
  Widget build(BuildContext context) {
   return Container();
  }
  }

checkBeans(value) 并不意味着 this.gotXbeans = true/false。意思是值=true/false。变量“值”应该是局部变量或方法变量。

您可以更新您的代码。

List<bool> beans = [false, false, false, false, false];

checkBeans(int index, bool value) {
  setState(() {
    beans[index] = value;
  });
}

或者您可以创建这样的方法。 checkBeans1、checkBeans2、checkBeans3、checkBeans4、checkBeans5...

checkBeans1(bool value) {
  setState(() {
    get1beans = value;
 });
}

如果您想传递参考,请勾选此question