1

我使用 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(),
              ),
            ),
          ],
        ),
      ),
    );
  }
}


4

1 回答 1

1

不幸的是,根据SpinBox 消息来源,没有简单的方法可以做到这一点。

值得庆幸的是,有一个解决方法:

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),
        ),
      ),
    );
  }
}
  • 将 a 分配GlobalKey给小部件(在本例中为 SpinBox)
  • 点击:
    • BaseSpinBoxState使用您之前创建的密钥提取状态
    • BaseSpinBoxStatefocusNode吸气剂,调用它并调用requestFocus
于 2021-03-21T15:35:34.333 回答