flutterdartspinbox

I want my onPressed method to open the keyboard of Spinbox


I use spinbox to set the number of break time in minutes. If you tap on the number a keyboard opens, and you can set your number. How do I open the Same keyboard of my spinbox, while pressing on the ElevatedButton?

I prepared the code for testing below, and I added (flutter_spinbox: ^0.4.0) to 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(),
              ),
            ),
          ],
        ),
      ),
    );
  }
}



Solution

  • Unfortunately, based on SpinBox sources, there's no easy way to do it.

    Thankfully, there's a workaround:

    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),
            ),
          ),
        );
      }
    }