我想把我的应用条的代码在我的 Scaffold
小部件到一个单独的类中。
我写了这个(编译后不能正确显示)。
class MyAppBar extends AppBar {
Widget build(BuildContext context) {
return AppBar(
title: const Text('Sample Code'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.menu),
tooltip: 'Navigation menu',
onPressed: null,
),
IconButton(
icon: Icon(Icons.search),
tooltip: 'Search',
onPressed: null,
),
],
);
}
}
class MyScaffold extends StatefulWidget {
_MyScaffoldState createState() => _MyScaffoldState();
}
class _MyScaffoldState extends State<MyScaffold> {
bool pressed = false;
Widget build(BuildContext context) {
return Scaffold(
appBar: MyAppBar(),
当这段代码编译后,正确地显示出AppBar,
class MyScaffold extends StatefulWidget {
_MyScaffoldState createState() => _MyScaffoldState();
}
class _MyScaffoldState extends State<MyScaffold> {
bool pressed = false;
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Sample Code'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.menu),
tooltip: 'Navigation menu',
onPressed: null,
),
IconButton(
icon: Icon(Icons.search),
tooltip: 'Search',
onPressed: null,
),
],
),
有谁能帮我解决这个问题吗?
答案在这里。单独处理应用栏
我需要 class MyAppBar extends StatelessWidget
将要 class MyAppBar extends StatelessWidget implements PreferredSizeWidget
试着用这个类代替你的MyAppBar类。
class MyAppBar extends StatefulWidget {
_MyAppBarState createState() => _MyAppBarState();
}
class _MyAppBarState extends State<MyAppBar> {
Widget build(BuildContext context) {
return AppBar(
title: const Text('Sample Code'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.menu),
tooltip: 'Navigation menu',
onPressed: null, // null disables the button
),
// Expanded expands its child to fill the available space.
IconButton(
icon: Icon(Icons.search),
tooltip: 'Search',
onPressed: null,
),
],
);
}
}
在制作自己的小部件时,一定要扩展无状态或有状态。