繁体   English   中英

如何在 Flutter 中制作具有不同功能的可重复使用容器

[英]How to make reusable containers with different features in Flutter

您好,我正在使用容器使 AppBar 具有彩色渐变代码是

Container appBarGradient(){
  return Container(
      decoration: BoxDecoration(
          gradient: LinearGradient(
              begin: Alignment.bottomLeft,
              end: Alignment.topRight,
              colors: <Color>[Colors.red, Colors.white, Colors.blue])));
}

我还在构建一个底部 AppBar 并希望使渐变保持一致的颜色,因此我正在重用 appBarGradient。 但我想向 appBarGradient 添加一个子对象,我注意到它有一个 .child 方法,但我不知道如何使用它。

BottomAppBar mainBottomBar(){
  return BottomAppBar(
    child: appBarGradient().child

  );
}

这些方法有什么用? 我可以使用它们在已有的小部件之上构建吗? 我什至不知道这叫什么,所以我很难在文档中搜索我要找的东西。 谢谢!

不确定这是否是您要查找的内容,但您可以制作这样的Gradient小部件:

class Gradient extends StatelessWidget {
  final Widget child;
  
  Gradient({this.child, Key key}) : super(key: key);
  
  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
          gradient: LinearGradient(
              begin: Alignment.bottomLeft,
              end: Alignment.topRight,
              colors: <Color>[Colors.red, Colors.white, Colors.blue])),
      child: child);
  }
}

然后你可以像使用任何其他小部件一样使用它,如下所示: Gradient(child: Text("I'm an example"))

不同的屏幕可以这样使用不同的渐变色。 您可以将颜色分配给您想要的不同屏幕

class Gradient extends StatefulWidget {
  final Widget child;
  List<Color> color =[];

  Gradient({this.child, Key key,this.color}) : super(key: key,);

  @override
  _GradientState createState() => _GradientState();
}

class _GradientState extends State<Gradient> {
  @override
  Widget build(BuildContext context) {
    return Container(
        height: 100,
  width: MediaQuery.of(context).size.width,
        decoration: BoxDecoration(
            gradient: LinearGradient(
                begin: Alignment.centerLeft,
                end: Alignment.centerRight,
                colors: widget.color
            )
        ),
        child: widget.child);
  }
}

暂无
暂无

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

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