如何在另一个类中使用一个类中的变量?

时间:2019-09-06 11:03:21

标签: variables methods flutter dart

我想在我的ChangeDrawModeState类中使用“ bool DrawMode”。

我需要“ GridState.drawMode”之类的东西,但是不起作用(drawMode在GridState中定义)。

最后,如果RaisedButton被按下,我需要更改变量drawMode。我不确定如何执行此操作,导致setState在ChangeDrawModeState类中也不起作用。但是,难道没有一种简单的方法来构建将Button的布尔值从True变为false(或相反)的Button吗?

class ChangeDrawMode extends StatefulWidget{
  @override
  ChangeDrawModeState createState(){
    return new ChangeDrawModeState();
  }
}

class ChangeDrawModeState<ChangeDrawMode>{
  @override
  Widget build(BuildContext context) {
    return new RaisedButton(
      child: new Text('Change Mode'),
      textColor: Colors.white,
      color: GridState.drawMode ? Colors.grey : Colors.blue,//HERE
      onPressed: () =>setState(() => drawMode = !drawMode) //and HERE drawMode does not work
    );
  }
}

class Grid extends StatefulWidget {
  @override
  GridState createState() {
    return new GridState();
  }
}

class GridState extends State<Grid> {
  bool drawMode = false;
  final Set<int> selectedIndexes = Set<int>();
  final key = GlobalKey();
  final Set<_Foo> _trackTaped = Set<_Foo>();

  _detectTapedItem(PointerEvent event) {
    final RenderBox box = key.currentContext.findRenderObject();
    final result = BoxHitTestResult();
    Offset local = box.globalToLocal(event.position);
    if (box.hitTest(result, position: local)) {
      for (final hit in result.path) {
        /// temporary variable so that the [is] allows access of [index]
        final target = hit.target;
        if (target is _Foo /*&&  !_trackTaped.contains(target)*/) {
          _trackTaped.add(target);
          _selectIndex(target.index);
        }
      }
    }
  }

  _selectIndex(int index) {
    setState(
    () {
      if(selectedIndexes.contains(index)&&drawMode==false){       
        selectedIndexes.remove(index);     
      }
      else if(drawMode==true){
        selectedIndexes.add(index);
      }

    });
  }

1 个答案:

答案 0 :(得分:1)

您可以使用InheritedWidget更新数据,从而更新应用程序任何部分的小部件状态

Here is an example