【问题标题】:Flutter: should I use variables or create a new class for sub widgets?Flutter: should I use variables or create a new class for sub widgets?
【发布时间】:2022-12-27 19:55:08
【问题描述】:

I'm currently working on a dashboard for my project. For my scaffold body I use a ListView. Should his childen be new classes or variables?

Example:

My Dashboard:

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        children: [
          const DashboardHeader(),
          DashboardSearch,
        ],
      ),
    );
  }

Dashboard Header as class:

class DashboardHeader extends StatelessWidget {
  const DashboardHeader({super.key});

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: MediaQuery.of(context).size.width,
      child: CarouselSlider(
        options: CarouselOptions(
          initialPage: 1,
          aspectRatio: 1,
          enableInfiniteScroll: true,
          autoPlay: true,
          autoPlayInterval: const Duration(seconds: 6),
        ),
        items: const [Text("Welcome"), Text("NEWS")],
      ),
    );
  }
}

DashboardSearch as variable:

Widget DashboardSearch = Padding(
  padding: const EdgeInsets.all(20.0),
  child: Column(
    children: const [
      Text("How can I help you?"),
      TextField(
        decoration: InputDecoration(suffixIcon: Icon(Icons.search)),
      ),
    ],
  ),
);

【问题讨论】:

    标签: flutter-layout flutter-design


    【解决方案1】:

    You can use dashboard header as a class

    Reason:

    When we have a large layout, then what we usually do is split using methods for each widget. But whenever we extract a widget as a method it is considered to be a pretty bad pattern(anti-pattern) because of the following reasons:

    1. If you are in a Stateful Widget and the set state is triggered, then it will also refresh the widgets that we have within the method, which leads us to waste CPU cycles.
    2. If you see the widget tree in dart developer tools, you can notice that you can’t distinguish between your extracted method.

      Therefore, always extract in Stateless / Stateful Widget instead of returning them in methods.

      Hope it solved your query.

    【讨论】:

      猜你喜欢
      • 2022-12-01
      • 2020-05-12
      • 2022-11-09
      • 2022-11-09
      • 1970-01-01
      • 1970-01-01
      • 2022-12-28
      • 2017-02-26
      • 2022-12-27
      相关资源
      最近更新 更多