如何通过颤振中的方法输入更新/设置状态布尔值?

时间:2021-04-28 21:59:50

标签: function flutter dart input boolean

这个可能有一个非常简单的答案,但我试图解决这个问题已经被阻止了一段时间并且无法真正让它发挥作用。

**问题:**当我使用 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();
  }
  }

1 个答案:

答案 0 :(得分:0)

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

您可以更新您的代码。

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