[英]How do I turn this hardcoded widget into a reusable & modular widget with proper function parameter?
我對如何解決這個問題感到非常困惑,甚至不認為我有正確的術語。 我缺乏這些基本的 Flutter 知識。
我想讓這個頁面小部件模塊化,這樣它就可以在很多地方使用,只有一個函數參數。 至少我認為那是我需要的。 我希望能夠將一個函數傳遞給這個可重用的自定義小部件,該小部件帶有用於構建的索引,以及索引,直到 indexCount。 索引計數將傳遞給 sliver 列表小部件中的子計數。 這樣傳遞的小部件將使用來自 sliver 構建器的索引參數構建。
/// WHAT I CURRENTLY HAVE
class PageOne extends StatelessWidget {
final int indexCount;
Widget sliverItem({required Widget child, required int index}) {
return child;
}
const PageOne({Key? key, required indexCount}) : super(key: key);
@override
Widget build(BuildContext context) {
return SafeArea(
child: Row(
children: [
const SizedBox(width: 40.0),
Consumer(builder: (context, ref, child) {
return Expanded(
child: EasyRefresh.custom(
onRefresh: // TODO
onLoad: // TODO
slivers: [
SliverList(
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return Card(
margin: const EdgeInsets.all(15),
child: Container(
color: Colors.blue[100 * (index % 9 + 1)],
height: 80,
alignment: Alignment.center,
child: const Text(
'item $index',
style: TextStyle(fontSize: 30),
),
),
);
},
childCount: indexCount,
),
),
],
),
);
}),
],
),
);
}
}
/// WHAT I THINK I NEED
class PageOne extends StatelessWidget {
final int indexCount;
Widget sliverItem({required Widget child, required int index}) {
return child;
}
const PageOne({Key? key, required indexCount}) : super(key: key);
@override
Widget build(BuildContext context) {
return SafeArea(
child: Row(
children: [
const SizedBox(width: 40.0),
Consumer(builder: (context, ref, child) {
return Expanded(
child: EasyRefresh.custom(
onRefresh: // TODO
onLoad: // TODO
slivers: [
SliverList(
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return sliverItem(index) // returns custom widget with index until indexCount
},
childCount: indexCount,
),
),
],
),
);
}),
],
),
);
}
}
與您聲明final int indexCount;
方式相同final int indexCount;
, 你可以將一個函數聲明為final Function() myFunction;
並在您想要的地方調用myFunction
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.