“异体,
我的主要文件是最多1000行代码,我不禁想到我可以通过将Scaffold分成3或4个.dart文件来节省时间。这可能吗?
在AppBar和Drawer之间由于所有链接和设计参数,我已经有多达500行代码。我想解开这段代码,而不是在我正在处理主体时不断滚动它。
每当我试图取出抽屉并把它放在一个单独的文件中时,我到处都会遇到错误。 “动态”和“小部件”以及返回类型等问题
我可以取出脚手架并将其引用到另一个文件中?
child: new Scaffold(
appBar: new AppBar(
bottom: new TabBar(tabs:[.....]),
actions: <Widget> [
new PopupMenuButton<xx>()
],),],), //end appBar
drawer: new Drawer(......), //end drawer
body: TabBarView(....), //end body
), //end scaffold
我不介意将主体留在这个主文件中,但如果我有更多的选择,我也可以把它拿出来。只想将1000多行减少到2-3个块,即可管理空间的文件。
有任何想法吗?
肯定有一种方法可以跨不同的文件组织它。除了更容易维护和测试之外,如果涉及状态,这也可以提高性能(因为如果状态改变,则必须重建整个树而不是仅重建叶节点)。
但是,这也意味着如果你有一个状态参与并在你的一个大型build()
方法中撒上,那么你可能会在组织文件时有一些额外的注意事项。这假设您将创建新的自定义小部件来包装各种组件,您需要适当地协调状态。
因此,为了将此构建方法分解为不同的子窗口小部件,我建议您首先将其分解为函数:
从:
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
bottom: new TabBar(tabs:[.....]),
actions: <Widget> [
new PopupMenuButton<xx>()
],),],), //end appBar
drawer: new Drawer(......), //end drawer
body: TabBarView(....), //end body
);
}
至:
Widget build(BuildContext context) {
return new Scaffold(
appBar: _appBar(),
drawer: _drawer(),
body: _body(),
);
}
Widget _appBar() {
return new AppBar(
bottom: new TabBar(tabs:[.....]),
actions: <Widget> [
new PopupMenuButton<xx>()
],),],);
}
Widget _drawer() {
...
}
Widget _body() {
return TabBarView();
}
此时,您可能会开始意识到要传递的数据/状态,因为您必须向这些新的辅助方法添加参数。
如果你有很多参数传递(特别是在更改的状态),你将有其他考虑因素超出这个答案的范围(我们需要看看你实际处理的状态)。
下一步是为每个方法创建一个新的Widget。
从:
Widget _appBar() {
return new AppBar(
bottom: new TabBar(tabs:[.....]),
actions: <Widget> [
new PopupMenuButton<xx>()
],),],);
}
至:
Widget _appBar(...) {
return MyAppBar(...);
}
class MyAppBar extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new AppBar(
bottom: new TabBar(tabs:[.....]),
actions: <Widget> [
new PopupMenuButton<xx>()
],),],);
}
}
您可以在其自己的文件中定义MyAppBar
。
你也可以绕过_appBar(...)
方法,只需在主要的build()
方法中构建新的小部件(假设你没有其他复杂的设置):
Widget build(BuildContext context) {
return new Scaffold(
appBar: MyAppBar(),
drawer: MyDrawer(),
body: _body(), // you might want to keep the body in the same file
);
}
方法最简单:
Widget build(BuildContext context) {
return Scaffold(
appBar: _buildAppBar(),
...
);
}
Widget _buildAppBar() {
return AppBar(...);
}
您还可以使用单独的小部件。 appBar
插槽中的小部件必须实现PreferredSizeWidget
:
class TestPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: MyAppBar(),
body: MyBody(),
);
}
}
class MyAppBar extends StatelessWidget implements PreferredSizeWidget {
@override
Size get preferredSize => Size.fromHeight(kToolbarHeight); // whatever height you want
@override
Widget build(BuildContext context) {
return AppBar();
}
}
class MyBody extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
child: Center(
child: Text('Hello World'),
),
);
}
}
当然,如果将它们放在不同的文件中,则必须将其导入:
import 'package:myapp/widgets/some_widget.dart';