flutter - 如何在 flutter 中正确重用小部件样式?

标签 flutter dart flutter-layout

来自 angular、react 和 vue 等前端网络框架,我正在努力寻找编写可重用小部件样式的最佳方法。让我用一个例子来说明这个问题。

假设我们有这个小部件:

Container(
  width: 25,
  height: 10,
  decoration: BoxDecoration(
    color: const Color(0xff7c94b6),
    border: Border.all(
      color: Colors.black,
      width: 8.0,
      ),
    ),
  child: /* some custom widget */,
);

现在假设我想做 Container width 等属性, height等可通过参数更改。如果未传递某个属性的某个参数,则应使用其默认值,如下所示:
class CustomWidget extends StatelessWidget {
  final double width;
  final double height;
  final BoxDecoration decoration;

  const CustomWidget ({
    Key key,
    this.width = 25,
    this.height = 10,
    this.decoration = /* default decoration */
    /* possibly even more properties */
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: width,
      height: height,
      decoration: decoration,
      child: /* some custom widget */
  }
}

显然,可能有更多的属性会导致越来越多的样板。另外,如果容器默认没有装饰,你会怎么做?你应该总是传递一个自定义容器吗?还要考虑容器可以嵌套在小部件树的下方。

一定有好的解决方案,就是想不出来,可能是因为我的前端开发经验,我的想法有偏见。在 web 项目中,您只需传递组件/小部件自定义 css 类来覆盖样式(例如参数 containerClasses )。你如何在 flutter 中正确地做到这一点?

编辑:从本质上讲,我的问题是:flutter 中是否有与 css 类等效的东西?或者:使自定义小部件的样式完全由参数自定义的最佳方法是什么。我觉得我必须手写每一个属性。

在 react 中,您有一个用于所有 html 元素的接口(interface)(例如 divinput 等)及其 Prop (例如,对于 input -元素,您有一个与 valueclasstype 的接口(interface)等),您可以使用它来定义可以传递哪些参数来自定义组件/小部件。

最佳答案

Flutter 样式的行为类似于 Vue 作用域样式/React“样式化组件”或 React Native:

在这些场景中没有“全局风格”。相反,您使用合成来获得所需的结果。

从某种意义上说,每个“CSS 类”都有一个 StatelessWidget,而不是一个带有许多参数的大 StatelessWidget。

例如,假设我们想将“红色背景 + 边框半径”拆分为可重用的样式,那么我们通常会有两个小部件:

  • 红色背景
  • 我的边境

  • 然后您可以在其中独立使用它们:

    RedBackground(
      child: Text('hello world'),
    )
    

    或一起:

    RedBackground(
      child: MyBorder(
        child: Text('hello world'),
      ),
    )
    

    关于flutter - 如何在 flutter 中正确重用小部件样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57939186/

    相关文章:

    flutter - 如何解决Build失败并出现异常?

    flutter - 游戏控制台 : Flutter App You can't rollout this release because it doesn't allow any existing users to upgrade to the newly added app bundles

    java - Dart:如何设置项目

    flutter - 如何在Flutter中自定义showDatePicker

    flutter - 为什么在脚手架的背景下会出现一个巨大的灰色圆圈?

    flutter - 在 flutter 自定义 ScrollView 中构建两个不同的列表

    flutter - flutter 中 GridView.builder 中带有标题的圆形卡

    javascript - 当 pub.dev 插件没有 web 支持时,使用 npm packages for flutter web

    flutter - 通过在列内使用堆栈,底部被无限像素溢出

    dart - 在 Flutter 中将图像对齐到左上角