为什么我的自建窗口小部件的命名参数在Flutter中不起作用?

问题描述 投票:0回答:1

我想将嵌套的Padding / Container / Padding结构包装在它自己的Widget中,以便我可以重用它:

我通过以下方式声明我的窗口小部件:

class UpperWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Container(
          width: this.width,
          child: Padding(padding: const EdgeInsets.all(8.0), child: child)),
    );
  }

  final double width;
  final Widget child;

  const UpperWidget(Key key, this.width, this.child) : super(key: key);
}

我想在以下地方使用它:

class LowerWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return UpperWidget(
      width:50,
      child: Text("Hello World");
      }),
    );
  }
}

当我将鼠标悬停在宽度上时,Android Studio会向我显示错误:

3 required argument(s) expected but 0 found
Try adding additional required arguments.

The named parameter 'width' isn't defined.
Try correcting the name to an existing parameter, or defining a parameter with this name.

我该怎么办,以便widthchild被正确地视为已命名参数?

flutter dart
1个回答
1
投票
您需要将它们用大括号optional包裹起来以使其成为{}

class UpperWidget extends StatelessWidget { @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(8.0), child: Container( width: this.width, child: Padding(padding: const EdgeInsets.all(8.0), child: child)), ); } final double width; final Widget child; const UpperWidget({Key key, this.width, this.child}) : super(key: key); }

如果还需要它们,则可以包含@required注释:

const UpperWidget({Key key, @required this.width, @required this.child}) : super(key: key);

© www.soinside.com 2019 - 2024. All rights reserved.