flutter - 当文本字段获得焦点并出现键盘时,为什么它会导航我回到上一个屏幕?

标签 flutter mobile flutter-layout flutter-dependencies flutter-test

我有一个简单的应用程序,它包含以下屏幕:

登陆屏幕 登录屏幕 验证屏幕

当尝试在验证屏幕上写东西时,当键盘出现并且文本字段获得焦点时,键盘会自动关闭,它会将我导航回登录屏幕而不会出现任何错误或错误。 我不知道为什么会这样?

信息:我在物理机和模拟器上运行应用程序,但没有任何区别,flutter 版本是 2.0.3,dart 2.12.2

这里是 flutter 医生:

Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.0.3, on Microsoft Windows [Version 
10.0.18363.1440], locale en-US)
[√] Android toolchain - develop for Android devices (Android SDK version 
30.0.3)
[√] Chrome - develop for the web
[√] Android Studio (version 4.1.0)
[√] IntelliJ IDEA Ultimate Edition (version 2020.2)
[√] VS Code (version 1.53.2)
[√] Connected device (3 available)

这是main的代码库:

void main() async {
WidgetsFlutterBinding.ensureInitialized();

runApp(
MyApp(),
);
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GetMaterialApp(
  title:TextConstants.appName,
  debugShowCheckedModeBanner: false,
  home: LandingScreen(),
  initialRoute: '/landing-screen',
  defaultTransition: Transition.downToUp,
  getPages: [
    GetPage(
      name: '/landing-screen',
      page: () => LandingScreen(),
    ),
    GetPage(
      name: '/login-screen',
      page: () => LoginScreen(),
    ),
    GetPage(
      name: '/verification-screen',
      page: () => VerificationScreen(),
    ),
  ],
);
}
}

这是登陆屏幕的代码库:

 @override
void didChangeDependencies() async {
super.didChangeDependencies();

if( await NetworkingUtils.checkInternetConnection()){
  // if it's connected.
  Get.toNamed("/login-screen");
} else {
  // if it's not connected.
  Get.snackbar(
    'Warning', // title
    'You don\'t have internet connection',
    icon: Icon(Icons.warning,color: Colors.white,),
    snackPosition: SnackPosition.BOTTOM,
    borderRadius: 0,
    showProgressIndicator: true,
    mainButton: TextButton(onPressed: (){}, child: Text('Check')),
    colorText: Colors.white,
    forwardAnimationCurve: Curves.bounceIn,
    isDismissible: false,
    reverseAnimationCurve: Curves.easeInOut,

  );
}

}

@override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;
return Scaffold(
  backgroundColor: Colors.lightBlueAccent,
  body: Container(
    decoration: BoxDecoration(
      image: DecorationImage(
        image: AssetImage('assets/images/landing_background.png'),
        fit: BoxFit.fill
      )
    ),
    child: Center(
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: AvatarGlow(
          glowColor: Colors.white,
          endRadius: width*0.44,
          showTwoGlows: true,
          repeat: true,
          duration: Duration(milliseconds: 1000),
          animate: true,
          child: ClipRRect(
            borderRadius: BorderRadius.circular(200.0),
            child: Container(
              height: width*0.6,
              width: width*0.6,
              child: Image.asset('assets/images/smart_city_logo.png'),
            ),
          ),
        ),
      ),
    ),
  ),
);
}
}

这是登录屏幕的代码库:

class LoginScreen extends StatefulWidget {
@override
_LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {

TextEditingController _phoneNumberController = TextEditingController();
bool isLoading = false;


@override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;
return Scaffold(
  backgroundColor: Colors.white,
  body: SafeArea(
    child: SingleChildScrollView(
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 20, vertical: 30),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            
 Image.asset('assets/images/smart_city_logo_transparent.png',height: width/2.5,fit:  BoxFit.fill,),
            SizedBox(height: 15,),
            Text("LOGIN TO", style: FontConstants.k24Light(fontSize: 38, textColor: Colors.black),),
            Text("SMART CITY \nMANAGER", style: FontConstants.k24Bold(fontSize: 35, textColor: ColorConstant.blueLight),textAlign: TextAlign.start,),
            Divider(height: 15,color: Colors.black, endIndent: width * 0.80, thickness: 3,),
            Text("Smart city manager provides whole information about the flat that you are looking for.", style: FontConstants.k24Light(fontSize: 20, textColor: Colors.black ).copyWith(wordSpacing: 0.5),),
            SizedBox(height: 35,),
            TextField(
              style: FontConstants.k24Light(fontSize: 20, textColor: Colors.black),
              decoration: InputDecoration(
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.all(
                    Radius.circular(10)
                  ),
                  borderSide: BorderSide(
                    width: 0,
                    style: BorderStyle.none
                  )
                ),
                filled: true,
                fillColor: ColorConstant.blueGreyLight,
                prefixIcon: Icon(Icons.phone_android_sharp, color: Colors.grey,),
                hintText: "Phone number...",
              ),
            ),
            SizedBox(height: 35,),
            RaisedGradientButton(
              child: Text(
                'NEXT',
                style: FontConstants.k24Light(
                    fontSize: 28, textColor: Colors.white),
              ),
              onPressed: () {
                Get.toNamed('/verification-screen');
              },
              gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [
                    Color(0xff7CD9FF),
                    Color(0xff3CC6FF),
                  ]),
            )
          ],
        ),
      ),
    ),
  ),
);
}
}

这是最后一个仅包含一个文本字段的代码库:

class VerificationScreen extends StatefulWidget {
@override
_VerificationScreenState createState() => _VerificationScreenState();
}

class _VerificationScreenState extends State<VerificationScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
    body: Container(
  child: Center(
    child: TextField(),
  ),
));
}
}

最佳答案

我在着陆屏幕上遇到了问题,它弄乱了小部件树。 因为 didChangeDependancy 方法会被多次调用,并且会随着小部件树的任何更改而被调用。 解决方案是 didChangeWidget 而不是 didChangeDependancy 并将导航更改为 offAndToNamed。

关于flutter - 当文本字段获得焦点并出现键盘时,为什么它会导航我回到上一个屏幕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66905528/

相关文章:

flutter - 格 subview 构建器,其项目的随机宽度 flutter

dart - 如何为整个 MaterialApp 的主题设置背景颜色?

flutter - 在同一页面上有 2 个具有相同手势的手势检测器

java - 快速将 int[] 写入磁盘?

mobile - Gluon Mobile 信息消息,如 Android Toast

flutter - TextField 的背景图片 - Flutter

dart - 如何在 ListView 的顶部插入小部件?

android - flutter View : AppBarLayout$ScrollingViewBehavior

android - OrientationEventListener (Tablet vs Mobile) 90度差异

android - Flutter:Raw Material Button 和 Material Button 的区别