如何停止StatefulWidget中的变量更改?

时间:2019-02-08 01:39:05

标签: dart flutter

每次调用setstate时,randomSel变量List都会更新,我想停止此操作

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MyColorBook();
  }
}

class MyColorBook extends State<MyApp> {
  List randomSel = new List<int>.generate(16, (int index) => index + 1);
  var accepted = List<bool>.generate(16, (i) => false);
  initState() {
    super.initState();
  }

1 个答案:

答案 0 :(得分:0)

您可以将其置于类之外,以使其成为全局变量:

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MyColorBook();
  }
}

List randomSel = new List<int>.generate(16, (int index) => index + 1);
var accepted = List<bool>.generate(16, (i) => false);

class MyColorBook extends State<MyApp> {

  initState() {
    super.initState();
  }

或者您可以将这些数据放在一个类中:

class Data{
    List randomSel = new List<int>.generate(16, (int index) => index + 1);
    var accepted = List<bool>.generate(16, (i) => false);}

,如果您想访问它: 初始化数据:

Data data = Data();

并通过以下方式访问randomSel:

data.randomSel