flutter
flutter

Reputation: 6786

Dismiss keyboard when swiping between pages in PageView

I'm trying to dismiss the keyboard between swiping between screen2(has a textfield) and screen1 using the PageView widget. I've tried calling Focus.of(context).unfocus(); in the dispose method of screen 2.But the keyboard remains.. Here's a minimum example...

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: Scaffold(
          appBar: AppBar(
            title: const Text('Welcome to Flutter'),
          ),
          body: PageView(
            children: [
              Screen1(),
              Screen2(),
            ],
          )),
    );
  }
}

class Screen1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text("Screen1");
  }
}

class Screen2 extends StatefulWidget {
  @override
  _Screen2State createState() => _Screen2State();
}

class _Screen2State extends State<Screen2> {

  @override
  void dispose() {
   Focus.of(context).unfocus();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return
     
           Column(
        children: [
          Text("Screen2"),
          TextField()
        ],
      
    );
  }
}

Upvotes: 3

Views: 3295

Answers (1)

Jesus Coronado
Jesus Coronado

Reputation: 146

If you want to dismiss the keyboard when you're swiping on pages, you can use onPageChanged property, using WidgetsBinding.instance?.focusManager.primaryFocus?.unfocus() will be executed when the user scroll every page and there exist a focus.

I took your code and modified.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Welcome to Flutter'),
        ),
        body: PageView(
          onPageChanged: (index) {
            WidgetsBinding.instance?.focusManager.primaryFocus?.unfocus();
          },
          children: [
            Screen1(),
            Screen2(),
          ],
        )
      ),
    );
  }
}

class Screen1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text("Screen1");
  }
}

class Screen2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text("Screen2"),
        TextField()
      ],
    );
  }
}

Upvotes: 6

Related Questions