首页 > 解决方案 > 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(),
  },

谢谢

标签: flutterfocusandroid-tvd-pad

解决方案


带有手势检测器的卡和ElevatedButton没有FocusNode.

如果你深入研究 the 的实现细节,ElevatedButton你会发现它使用了一个InkWellwith 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: // ...
          ),
        ),
      ),
    ),
  ),
);

因此,如果您替换GestureDetectorInkwell,则键盘导航将起作用。

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 上测试,带有键盘和方向键。)

参考


推荐阅读