简体   繁体   English

Flutter 重构结构

[英]Flutter refactor structure

I saw somewhere online that when refactoring widgets in Flutter, you should opt for refactoring them as classes rather than methods.我在网上看到,在 Flutter 中重构小部件时,您应该选择将它们重构为类而不是方法。 So I wonder if having my page structured like this is bad Flutter practice.所以我想知道我的页面结构是否像这样是不好的 Flutter 做法。

And if so, why?如果是这样,为什么? Because it looks cleaner this way in my opinion.因为在我看来,这样看起来更干净。

class ProfilePage extends StatefulWidget {
  bool isUserProfile;

  ProfilePage(this.isUserProfile, {Key? key}) : super(key: key);

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

///
///Page state class
///
class _ProfilePageState extends State<ProfilePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Stack(
     
        children: [
          _profileBanner(),
          _whiteBackgroundContainer(),
          _profileImage(),
          _userName(),
          _backArrow(),
          _profilePageButtons(),
          _reputationBuble(),
          _friendsAndGamesCounter(),
          _personnalnformationRow(),
          _divider(),
          _biographyTile(),
        ],
      ),
    );
  }

 
}
  1. Refactor into method重构为方法
Text buildHello() => Text('Hello');
  1. Refactor into widget重构为小部件
class HelloWidget extends StatelessWidget {
  const HelloWidget({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Text('Hello');
  }
}

Now refactoring into method might seem tempting here but when buildHello is too big it might rebuild even when nothing inside buildHello was changed.现在重构为方法在这里似乎很诱人,但是当 buildHello 太大时,即使 buildHello 内部没有任何更改,它也可能会重建。 But when it comes to refactoring into widget, we get all the benefits of widget lifecycle so it will rebuild only when something in widget changes.但是当谈到重构到小部件时,我们获得了小部件生命周期的所有好处,因此它只会在小部件中的某些内容发生变化时重建。 So this prevents unnecessary rebuilds and thus improving the performance.因此,这可以防止不必要的重建,从而提高性能。 This also offers all the optimizations that Flutter offers for widget class.这也提供了 Flutter 为小部件 class 提供的所有优化。

source link链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM