我是Flutter和Dart的新手,并且正在尝试基于以下内容创建可点击的容器类:
GestureDetector类。我的容器代码如下所示:
class CustomWidget extends GestureDetector
{
final aTitle;
CustomWidget(this.aTitle)
{
onTap() {
print("$aTitle was pressed!");
}
child: new Container(
padding: const EdgeInsets.all(8),
child: Text(aTitle),
color: Colors.blueGrey[200],
);
}
}
我正在尝试使用应用程序小部件主体中的以下代码在主应用程序屏幕上显示此小部件: body: CustomScrollView(
primary: false,
slivers: <Widget>[
SliverPadding(
padding: const EdgeInsets.all(20),
sliver: SliverGrid.count(
crossAxisSpacing: 10,
mainAxisSpacing: 10,
crossAxisCount: 2,
children: <Widget>[
CustomWidget('Test Display'),
],
),
),
],
),
我似乎有两个问题:(1)我的开发环境告诉我onTap()方法“未使用”,表明它不会捕获点击事件,(2)似乎无关紧要,因为我是CustomWidget实例
在应用小部件中创建的内容未显示在我的屏幕上。
我显然缺少了一些东西。有人可以帮助我更正我的代码,以便显示和处理我的自定义小部件
onTap事件?
最佳答案
一般来说,CustomWidget是一个好主意,但是继承是错误的实现。 Flutter强烈主张使用组合而不是继承。
使用合成的自定义小部件:
class CustomWidget extends StatelessWidget {
final String title;
const CustomWidget(this.title);
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
print("$title was pressed!");
},
child: new Container(
padding: const EdgeInsets.all(8),
child: Text(title),
color: Colors.blueGrey[200],
));
}
}
关于flutter - Flutter自定义窗口小部件无法显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63961467/