gpt4 book ai didi

dart - 单击 TextField 小部件时 Flutter 小部件重建

转载 作者:IT王子 更新时间:2023-10-29 07:03:50 25 4
gpt4 key购买 nike

我确定这是一个菜鸟错误,但我似乎无法弄清楚这个错误。在下面的应用程序中,当单击第二个路由中的文本字段时,键盘打开并立即关闭。经过仔细调查,似乎小部件在获得焦点时正在重建,导致路由重置,使用户无法输入文本。

当我从表单中删除“键”时,问题就不会发生。这不是长期修复,因为我需要“ key ”才能验证表单。

有什么想法吗?

import 'package:flutter/material.dart';


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

class MyApp extends StatelessWidget {

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My app',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.lightBlue,
fontFamily: 'Nunito',
),
home: LoginPage(),
);
}
}


class LoginPage extends StatefulWidget {

@override
LoginPageState createState() {
return new LoginPageState();
}
}

class LoginPageState extends State<LoginPage> {

Widget build(BuildContext context) {

final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

final registerButton = Padding(
padding: EdgeInsets.symmetric(vertical: 16.0),
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(24),
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondPage()),
);
},
child: Text('Register Now', style: TextStyle(color: Colors.white)),
),
);

// Now load the main login page
return Scaffold(
backgroundColor: Colors.white,
key: _scaffoldKey,
body: Center(
child: ListView(
shrinkWrap: true,
children: <Widget>[
registerButton,
],
),
),
);
}
}


class SecondPage extends StatelessWidget {

@override
Widget build(BuildContext context) {

final emailController = TextEditingController();
final _formKey = GlobalKey<FormState>();

final email = TextFormField(
keyboardType: TextInputType.emailAddress,
controller: emailController,
autofocus: false,
decoration: InputDecoration(
hintText: 'Email',
contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
border: OutlineInputBorder(borderRadius: BorderRadius.circular(32.0)),
),
);

return Scaffold(
appBar: AppBar(
title: Text('Second page'),
),
body: Center(
child: Form(
key: _formKey,
child: email,
),
),
);
}
}

最佳答案

您必须在构建方法之外将 _formKey 声明为静态。

关于dart - 单击 TextField 小部件时 Flutter 小部件重建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55474562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com