我想让我的 onPressed 方法打开 Spinbox 的键盘

I want my onPressed method to open the keyboard of Spinbox

我使用旋转框来设置休息时间的分钟数。如果您点击键盘打开的号码,您可以设置您的号码。如何在按下 ElevatedButton 的同时打开旋转框的同一个键盘?

我准备了下面的测试代码, 我将 (flutter_spinbox: ^0.4.0) 添加到 pubspec.yaml

import 'package:flutter/material.dart';
import 'package:flutter_spinbox/flutter_spinbox.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  int breaktime = 60;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("SpinBox")),
        body: Column(
          children: [
            Container(
              child: ElevatedButton(
                child: Text(
                  'Break in minutes',
                ),
                onPressed: () => {}, 
              ),
            ),
            Container(
              height: 35,
              child: SpinBox(
                min: 0,
                max: 120,
                value: 60,
                onChanged: (value) => breaktime = value.toInt(),
              ),
            ),
          ],
        ),
      ),
    );
  }
}


不幸的是,基于 SpinBox sources,没有简单的方法来做到这一点。

谢天谢地,有一个解决方法:

class MyApp extends StatelessWidget {
  final spinBoxKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: SpinBox(
            key: spinBoxKey,
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            final focusNode = (spinBoxKey.currentState as dynamic).focusNode as FocusNode;
            focusNode.requestFocus();
          },
          child: Icon(Icons.keyboard),
        ),
      ),
    );
  }
}
  • GlobalKey 分配给小部件(在本例中为 SpinBox)
  • 点击:
    • 使用您之前创建的密钥提取 BaseSpinBoxState 状态
    • BaseSpinBoxStatefocusNode getter,调用它并在其上调用 requestFocus