我想知道重用組件的最佳做法是什么:僅使用“小部件方法”還是使用具有無狀態/完整小部件的完整類創建檔案更好?
例如,我想重用 appbar,最佳做法是什么?
mainAppbar.dart
import 'package:flutter/material.dart';
import 'package:myapp/ressources/customColors.dart';
AppBar mainAppbar() {
return AppBar(
backgroundColor: Colors.white,
title: Text(
"Test",
style: TextStyle(color: CustomColors.mainColor),
),
actions: [
IconButton(
icon: Icon(Icons.search, color: CustomColors.mainColor),
onPressed: () {},
splashRadius: 20,
),
IconButton(
icon: Icon(Icons.tune, color: CustomColors.mainColor),
onPressed: () {},
splashRadius: 20,
),
],
);
}
要么
import 'package:flutter/material.dart';
import 'package:myapp/ressources/customColors.dart';
class MainAppBar extends StatelessWidget implements PreferredSizeWidget {
final AppBar appBar;
const MainAppBar({Key? key, required this.appBar}) : super(key: key);
@override
Widget build(BuildContext context) {
return AppBar(
backgroundColor: Colors.white,
title: Text(
"Test",
style: TextStyle(color: CustomColors.mainColor),
),
actions: [
IconButton(
icon: Icon(Icons.search, color: CustomColors.mainColor),
onPressed: () {},
splashRadius: 20,
),
IconButton(
icon: Icon(Icons.tune, color: CustomColors.mainColor),
onPressed: () {},
splashRadius: 20,
),
],
);
}
@override
Size get preferredSize => Size.fromHeight(appBar.preferredSize.height);
}
在此示例中,我使用了 appbar,但對于我想重用的所有其他組件來說,這是同一個問題 :)
還有一件事:我正在使用 GetX 包!
謝謝!
uj5u.com熱心網友回復:
Flutter的 youtube 頻道上有關于這個問題的非常好的資源。
小部件 vs 輔助方法 | 解碼顫振
您還可以從此處查看播放串列中的其他視頻
uj5u.com熱心網友回復:
我不太了解 getX 包,但我認為第一種方法更好,因為 appBar 中沒有任何變化,因此使用第一種方法更好,這樣每當你呼叫 build 方法時,你的 appBar 都不會重新- 呈現在螢屏上。
uj5u.com熱心網友回復:
我的事情是創建一個類是更好的方法,因為這樣你就可以將類用作小部件。
PS:我對 getX 包一無所知
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/431585.html
