flutter - Flutter 如何制作可选择/可聚焦的小部件
问题描述
我正在创建一个 android 电视应用程序。我试图弄清楚为什么当我单击遥控器上的向上和向下箭头按钮时它似乎什么也没做并且它没有选择任何列表项。
最终我发现如果我在列表中使用提升按钮或其他可聚焦的小部件,我可以使用箭头键,它会正常工作。以前我使用的是包裹在手势检测器中的卡片小部件。
所以我想知道按钮和带有手势检测器的卡片之间的区别是阻止箭头键选择项目。我怀疑这是焦点。
这就是我使用的不允许遥控器上的向上,向下键选择它:
GestureDetector(
child: Card(
color: color,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
elevation: 10,
child: SizedBox(
width: (width / numberOfCards) - padding * (numberOfCards - 1),
height: (height / 2) - padding * 2,
child: Center(child: Text(cardTitle, style: Theme.of(context).textTheme.bodyText1?.copyWith(fontSize: 16, fontWeight: FontWeight.bold, color: Colors.white),))),
),
onTap: () => onCardTap(),
),
这是我用它替换的按钮,然后使上下键和选择起作用:
ElevatedButton(
onPressed: () {},
child: Text('Test 1', style: Theme.of(context).textTheme.bodyText1?.copyWith(color: Colors.white, fontSize: 18, fontWeight: FontWeight.normal)),
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.grey.withOpacity(0.3)),
minimumSize: MaterialStateProperty.all(Size(60, 60)),
elevation: MaterialStateProperty.all(10),
shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: new BorderRadius.circular(50)),)),
),
如果需要,这就是我用来拾取按键的方法:
Shortcuts(
shortcuts: <LogicalKeySet, Intent>{
LogicalKeySet(LogicalKeyboardKey.select): const ActivateIntent(),
},
谢谢
解决方案
带有手势检测器的卡和ElevatedButton
没有FocusNode
.
如果你深入研究 the 的实现细节,ElevatedButton
你会发现它使用了一个InkWell
with aFocusNode
final Widget result = ConstrainedBox(
constraints: effectiveConstraints,
child: Material(
// ...
child: InkWell(
// ...
focusNode: widget.focusNode,
canRequestFocus: widget.enabled,
onFocusChange: updateMaterialState(MaterialState.focused),
autofocus: widget.autofocus,
// ...
child: IconTheme.merge(
// ....
child: Padding(
padding: padding,
child: // ...
),
),
),
),
),
);
因此,如果您替换GestureDetector
为Inkwell
,则键盘导航将起作用。
InkWell(
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
elevation: 10,
child: const SizedBox(
width: 200,
height: 60,
child: Center(
child: Text(
'Test 1',
),
),
),
),
onTap: () {},
)
(在 Android TV 模拟器 API 30 上测试,带有键盘和方向键。)
参考
推荐阅读
- android - 替换导航视图项目波纹效果
- swift - 在 UIContextualAction 中正确设置彩色图标
- python - 在单个任务中捕获异常并重新启动它们
- tensorflow - 如何将 numpy.ndarray 转换为 tfrecord?
- swift - Swift:将视图添加到窗口时不显示阴影
- html - 为什么我的引导轮播不工作?
- angular - ag-grid angular - 选择更改时刷新组行
- excel - If statement to flag only certain values?
- javascript - 如何在 Nativescript 应用程序中调用 axios/api 调用
- mysql - 使用 mysql 存储过程创建多个视图