在另一个 dart 文件中声明 AppBar 并用另一个文件实例化它
Declare AppBar in another dart file and instantiate it with an different file
这是我使用 Flutter 的第 4 天。我以前用Unity。
目前我的项目有 3 页; 主页、个人资料、设置
这些页面使用 Navigator
转换。
AppBar
在每个页面的 Scaffold
中声明,但所有页面的 AppBar
都是相同的。
所以我必须写三个相同的代码。 (以后页数增加总是需要写和修改相同的代码)
所以我认为将 AppBar 声明为变量看起来不错,页面只会调用它。
像这样:
//originappbar.dart
AppBar originAppBar(
backgroundColor: .....
)
//home.dart
class ShowHome extends StatelessWidget {
ShowHome({Key? key}) : super(key: key);
static const String route = '/home';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: originAppBar(), ....
//profile.dart
//Same as home.dart
在上面的示例中,我试图将 originappbar.dart
创建的 originAppBar
分配给 home.dart
或 profile.dart
中的 appbar:
。
但我不能将 AppBar 声明为变量。
我很困惑,因为我认为我可以让 AppBar 成为一个变量。
我的代码有什么问题?
谢谢。
PreferredSizeWidget originAppBar = new AppBar(
backgroundColor: .....
)
//home.dart
class ShowHome extends StatelessWidget {
ShowHome({Key? key}) : super(key: key);
static const String route = '/home';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: originAppBar, ....
//profile.dart
//Same as home.dart
您可以创建无状态小部件,例如:
class CustomAppBar extends StatelessWidget implements PreferredSizeWidget{
///Here goes your duplicated code
}
然后到处使用 CustomAppBar。
或者创建一个小部件 CustomScaffold
,它只不过是您在所有页面中使用的脚手架,但带有 CustomAppbar 和任何其他挂件。
这是我使用 Flutter 的第 4 天。我以前用Unity。 目前我的项目有 3 页; 主页、个人资料、设置
这些页面使用 Navigator
转换。
AppBar
在每个页面的 Scaffold
中声明,但所有页面的 AppBar
都是相同的。
所以我必须写三个相同的代码。 (以后页数增加总是需要写和修改相同的代码)
所以我认为将 AppBar 声明为变量看起来不错,页面只会调用它。 像这样:
//originappbar.dart
AppBar originAppBar(
backgroundColor: .....
)
//home.dart
class ShowHome extends StatelessWidget {
ShowHome({Key? key}) : super(key: key);
static const String route = '/home';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: originAppBar(), ....
//profile.dart
//Same as home.dart
在上面的示例中,我试图将 originappbar.dart
创建的 originAppBar
分配给 home.dart
或 profile.dart
中的 appbar:
。
但我不能将 AppBar 声明为变量。 我很困惑,因为我认为我可以让 AppBar 成为一个变量。 我的代码有什么问题?
谢谢。
PreferredSizeWidget originAppBar = new AppBar(
backgroundColor: .....
)
//home.dart
class ShowHome extends StatelessWidget {
ShowHome({Key? key}) : super(key: key);
static const String route = '/home';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: originAppBar, ....
//profile.dart
//Same as home.dart
您可以创建无状态小部件,例如:
class CustomAppBar extends StatelessWidget implements PreferredSizeWidget{
///Here goes your duplicated code
}
然后到处使用 CustomAppBar。
或者创建一个小部件 CustomScaffold
,它只不过是您在所有页面中使用的脚手架,但带有 CustomAppbar 和任何其他挂件。