在初始化器中只能访问静态成员

时间:2019-09-02 09:31:49

标签: flutter dart

我无法使用GlobalKey中的Scaffold。错误是

  

只能在初始化程序中访问静态成员

//Global key
  final GlobalKey<ScaffoldState> _mainKey= GlobalKey<ScaffoldState>();
// List of TabBar
final List<Widget> tabBar = <Widget>[
    Column(
      children: <Widget>[
        Icon(Icons.account_balance_wallet),
        Text('flutter'),
        Text('dart')
      ],
    ),
    FlatButton(
      child: Text('Open Drawer'),
      onPressed: (){
         //( _mainKey) has a red underLine color
        _mainKey.currentState.openDrawer();
      },
    )
  ];
/*
Compiler message:
lib/Trial.dart:32:9: Error: Can't access 'this' in a field initializer to read '_mainKey'.
        _mainKey.currentState.openDrawer();*/

1 个答案:

答案 0 :(得分:0)

简短答案

替换

final GlobalKey<ScaffoldState> _mainKey= GlobalKey<ScaffoldState>(); 

使用

static GlobalKey<ScaffoldState> _mainKey= GlobalKey<ScaffoldState>();

长答案:

我建议您将tabBar从变量更改为方法,这样就无需使变量static。喜欢:

List<Widget> getTabBar() {
  return [
    Column(
      children: <Widget>[Icon(Icons.account_balance_wallet), Text('flutter'), Text('dart')],
    ),
    FlatButton(
      child: Text('Open Drawer'),
      onPressed: () {
        _mainKey.currentState.openDrawer();
      },
    )
  ];
}