[英]Flutter - Cannot set an appbar as a widget to the scaffold
I want to create a responsive appbar without need to setState
to the entire scaffold when there are changes.我想创建一个响应式应用栏,而无需在有更改时对整个
setState
设置状态。 The problem is I can set a BottomNavigationBar
widget to the scaffold's bottomNavigationBar
but I can't do the same with an AppBar
to set to it's appBar
.问题是我可以将一个
BottomNavigationBar
小部件设置为脚手架的bottomNavigationBar
但我不能对AppBar
做同样的事情来设置它的appBar
。 I get this error我收到这个错误
The argument type 'TopBar' can't be assigned to the parameter type 'PreferredSizeWidget'
参数类型“TopBar”不能分配给参数类型“PreferredSizeWidget”
I've simplified the code with the State
s only part.我已经用
State
的唯一部分简化了代码。
class StateLayoutNav extends State<LayoutNav>{
@override
Widget build(BuildContext context) => Scaffold(
bottomNavigationBar : BottomBar(), appBar : TopBar()
);
}
class StateTopBar extends State<TopBar>{
@override
Widget build(BuildContext context) => AppBar();
}
class StateBottomBar extends State<BottomBar>{
@override
Widget build(BuildContext context) => BottomNavigationBar();
}
尝试appBar: TopBar() as PreferredSizeWidget
My solution would be implementing your Appbar widget with PreferredSizeWidget as Appbar need to be of preferredSize我的解决方案是使用 PreferredSizeWidget 实现您的 Appbar 小部件,因为 Appbar 需要具有 preferredSize
class TopBar extends StatefulWidget with PreferredSizeWidget {
TopBar({Key key}) : preferredSize = Size.fromHeight(kToolbarHeight), super(key: key);
@override
final Size preferredSize;
@override
StateTopBar createState() => StateTopBar();
}
class StateTopBar extends State<TopBar>{
@override
Widget build(BuildContext context) => AppBar();
}
Try this.尝试这个。 It will give you a custom app bar with any customisable widget.
它将为您提供带有任何可自定义小部件的自定义应用栏。 You can add fixed Container.
您可以添加固定容器。 Solution is implementing app bar with PreferredSizeWidget.
解决方案是使用 PreferredSizeWidget 实现应用栏。
class TopBar extends StatefulWidget implements PreferredSizeWidget {
TopBar({Key? key}) : preferredSize = Size.fromHeight(kToolbarHeight), super(key: key);
@override
final Size preferredSize; // default is 56.0
@override
_TopBarState createState() => _TopBarState();
}
class _TopBarState extends State<TopBar>{
@override
Widget build(BuildContext context) {
return Container( child: Text("Sample App Bar") );
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.