'How to avoid keyboard popping out while navigating to next screen?
When I navigate from LoginScreen() to HomeScreen() the keyboard pops up for no apparent reason for a split second and then immediately closes while the navigation is in progress.
The function that calls for the screen pushReplacement:
() async {
if (_formKey.currentState.validate()) {
final FirebaseAuth _auth = FirebaseAuth.instance;
try {
await _auth.signInWithEmailAndPassword(
email: email, password: password);
} catch (e) {
Scaffold.of(context).showSnackBar(SnackBar(
content: Text('Email or Password are incorrect'),
));
}
_user = await _auth.currentUser();
if (_user == null) {}
if (_user.isEmailVerified == true) {
Navigator.of(context)
.pushReplacementNamed(HomeScreen.routeName);
} else
Scaffold.of(context).showSnackBar(SnackBar(
content: Text('Validate your email pls!'),
));
}
},
and the HomeScreen():
import 'package:final_login/screens/loginscreen.dart';
import 'package:final_login/services/auth.dart';
import 'package:flutter/material.dart';
class HomeScreen extends StatefulWidget {
static const routeName = '/home-screen';
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Column(
children: <Widget>[
RaisedButton(
child: Text('Log out'),
onPressed: (){
AuthService().signOut();
Navigator.of(context).pushReplacementNamed(LoginScreen.routeName);
},
),
],
),
),
);
}
}
Solved by putting FocusScope.of(context).requestFocus(FocusNode());
before the function call.
Solution 1:[1]
Update:
The below answer is no longer the best way to do it after flutter update, this is the better way now:
FocusScope.of(context).unfocus();
Old answer
try this, it will remove the keyboard programmatically before pushing new page:
if (_user.isEmailVerified == true) {
FocusScope.of(context).requestFocus(FocusNode());
Navigator.of(context).pushReplacementNamed(HomeScreen.routeName);
}
Solution 2:[2]
Upper answer did not work for me. Just try this code before the navigation.
FocusScope.of(context).unfocus();
RaisedButton(
onPressed: () {
FocusScope.of(context).unfocus();
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (context) => HomeScreen(),
),
);
},
),
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |