我目前从 flutter 示例中获得了这段代码:
import 'package:flutter/material.dart';
import 'auth.dart';
class HomePage extends StatefulWidget {
HomePage({this.auth, this.onSignedOut});
final BaseAuth auth;
final VoidCallback onSignedOut;
State<StatefulWidget> createState() => new _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
void signOut() async {
try {
await widget.auth.signOut();
widget.onSignedOut();
} catch (e) {
print(e);
}
}
@override
int _selectedIndex = 0;
static const TextStyle optionStyle = TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
List<Widget> _widgetOptions = <Widget>[
Hero(
tag: "Login-Homepage",
child: Container(
child: new Text('Hello'),
),
),
Text(
'Lessons will go here',
style: optionStyle,
),
Text(
'Tasks will go here',
style: optionStyle,
),
Container(
child: new RaisedButton(
child: new Text('Sign Out'),
onPressed: signOut,
),
)
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(
elevation: 0.1,
title: const Text(
'Musiplan - Teachers Dash',
style: TextStyle(color: Colors.black),
),
backgroundColor: Colors.white,
),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Dashboard'),
),
BottomNavigationBarItem(
icon: Icon(Icons.calendar_today),
title: Text('Lessons'),
),
BottomNavigationBarItem(
icon: Icon(Icons.book),
title: Text('Tasks'),
),
BottomNavigationBarItem(
icon: Icon(Icons.settings),
title: Text('Settings'),
),
],
currentIndex: _selectedIndex,
selectedItemColor: Color(0xff455eba),
unselectedItemColor: Colors.black,
onTap: _onItemTapped,
),
);
}
}
但是,运行这段代码后,按钮的 onPressed: signout
属性上出现了 Only static members can be accessed in initializers.
。我试图在按下那个按钮时调用那个函数来调用那个函数,但我被它给我的错误困住了。将函数更改为 static void
只会给我留下更多错误。
有什么办法可以解决这个问题吗?
非常感谢。
最佳答案
这是因为您正在访问初始化程序中的某些方法(当您创建小部件列表时,这是一个初始化程序)。 尝试在 initState 方法中创建小部件列表。
List<Widget> _widgetOptions;
@override
void initState() {
_widgetOptions = <Widget>[
Hero(
tag: "Login-Homepage",
child: Container(
child: new Text('Hello'),
),
),
Text(
'Lessons will go here',
style: optionStyle,
),
Text(
'Tasks will go here',
style: optionStyle,
),
Container(
child: RaisedButton(
child: Text('Sign Out'),
onPressed: signOut,
),
)
];
super.initState();
}
关于flutter - 在不在构建方法中的小部件中使用按钮的回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57467466/