gpt4 book ai didi

Flutter GlobalKey 当前状态为空

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

我基本上想做的(我确实做了,详情在前面)是创建一个具有多种形式的屏幕,使用按钮 (NEXT) 更改其内容。所以我有 3 种形式,当我按下下一步时,我保存第一种形式并传递给另一种形式,当我把我的类(class)放在 main.dart 中时,我到目前为止所做的工作。例如,这是我的 main.dart 内容。

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

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Entries'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
static final _scafoldKey = new GlobalKey<ScaffoldState>();
final firstForm = new FirstForm(title: "First Form");
final secondForm = new SecondForm(title: "First Form",);
final thirdForm = new ThirdForm(title: "First Form");
final Map<int,Widget> forms = {};
final Map<String,Map> allValues = new Map();

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

Widget currentForm;
final Firestore _fireStore = Firestore.instance;
Map<String,Map> thirdFormNested = new Map();
int thirdFormPos = 1;

@override
void initState() {
widget.forms[0] = widget.firstForm;
widget.forms[1] = widget.secondForm;
widget.forms[2] = widget.thirdForm;
currentForm = widget.forms[0];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
key: MyHomePage._scafoldKey,
appBar: AppBar(
title: Text(widget.title),
leading: IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () => Navigator.of(context).pop(),
),
),
body: SingleChildScrollView(
child: currentForm,
),
floatingActionButton: Stack(
children: <Widget>[
Align(
alignment: Alignment(0.4, 1),
child: SizedBox(
width: 75,
child: FloatingActionButton(
shape: RoundedRectangleBorder(),
child: Text("NEXT"),
onPressed: () {
GlobalKey<FormState> key;
if(currentForm is FirstForm) {
key= widget.firstForm.formKey;
if(key.currentState.validate()){
key.currentState.save();
widget.allValues["First Form"] = widget.firstForm.values;
setState(() {
currentForm = widget.forms[1];
});
}
}
else if(currentForm is SecondForm) {
setState(() {
currentForm = widget.forms[2];
});
}
else if (currentForm is ThirdForm) {
key = widget.thirdForm.formKey;
if(key.currentState.validate()){
key.currentState.save();
var tmp = widget.thirdForm.values;
widget.thirdForm.values = <String,String>{};
thirdFormNested.addAll({"Bit $thirdFormPos":tmp});
key.currentState.reset();
widget.thirdForm.build(context);
thirdFormPos++;
}
}
},
),
),
),
Align(
alignment: Alignment(1, 1),
child: SizedBox(
width: 75,
child: FloatingActionButton(
shape: RoundedRectangleBorder(),
child: Text("SUBMIT"),
onPressed: () async {
GlobalKey<FormState> key;
if(currentForm is FirstForm) {
key= widget.firstForm.formKey;
if(key.currentState.validate()) {
key.currentState.save();
await _fireStore.collection('form').document(Uuid().v1()).setData(widget.firstForm.values);
}
}else if(currentForm is SecondForm) {
await _fireStore.collection('form').document(Uuid().v1()).setData(widget.firstForm.values);
}else if(currentForm is ThirdForm) {
key= widget.thirdForm.formKey;
if(key.currentState.validate()){
key.currentState.save();
if(thirdFormNested.length == 0) {
var tmp = widget.thirdForm.values;
widget.thirdForm.values = <String,String>{};
thirdFormNested.addAll({"Bit 1":tmp});
}else {
var tmp = widget.thirdForm.values;
widget.thirdForm.values = <String,String>{};
thirdFormNested.addAll({"Bit $thirdFormPos":tmp});
}
widget.allValues["Third Form"] = thirdFormNested;
await _fireStore.collection('form').document(Uuid().v1()).setData(widget.allValues);
}
}
},
),
),
),
],
)
);
}
}

这是第一种形式(其他形式相同,唯一不同的是输入):

class FirstForm extends StatelessWidget {
FirstForm({Key key, this.title}) : super(key: key);
final String title;
final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
Map<String,String> _values = new Map();

get formKey => _formKey;
get values => _values;
set values(v) => _values = v;

@override
Widget build(BuildContext context) {
print("FORM KEY: ${_formKey.currentState}");
_values['Spud Date'] = _formatDate(DateTime.now().toString());
_values['TD Date'] = _formatDate(DateTime.now().toString());
return Form(
key: _formKey,
child: Column(
children: <Widget>[
ListTile(
leading: Text(
"API#",
style: TextStyle(
fontSize: 18,
),
),
title: TextFormField(
decoration: InputDecoration(
hintText: "<api>"
),
validator: (value) {
if(value.isEmpty) {
return "Please enter API value!";
}
return null;
},
onSaved: (value) {
_values['API#'] = value;
},
),
..... Other inputs
Padding(
padding: EdgeInsets.symmetric(vertical: 36.0),
)
],
),
);
}

String _formatDate(String date) {
DateTime d = DateTime.parse(date);
return DateFormat("dd-MM-yyyy").format(d);
}
}

所以每个表单都有一个表单 key ,我将其传递给 Form(key: ..)。我实例化了 MyHomePage 类中的每个表单,并使用 widget.firstForm.formKey 检索表单 key 以将其用于验证。

到目前为止,这一直运行良好。但是,当我尝试将我的工作融入现有应用程序时。它不再存在了。

在现有的应用程序中,我有一个抽屉。抽屉中有一项名为 Forms,它将我带到我现在重命名为 Forms 的“MyHomePage”。所以代码仍然是一样的,我唯一删除的是 runApp() 和 MyApp 类,它们现在位于不同的文件中。这是抽屉元素代码:

ListTile(
title: new Text('Forms'),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
maintainState: true,
builder: (context) => Forms(title: "Forms")
),
);
},
),

现在,使用这个方法。在“表单”屏幕中单击“下一步”时,出现错误:

validate() called on null

所以几个小时后,我发现实际上是我的表单的 GlobalKey 返回了空状态。问题是为什么?我该如何解决这个问题。

TL;DR:我有 3 个表单及其各自的 GlobalKeys。这些键用于验证包装这些表单的另一个小部件中的表单。当我在 main.dart 的默认 MyHomePage 类中有包装器小部件时,我处理它们的方法就起作用了。但是,当将相同的包装器类移动到外部文件并将该类重命名为更合适的名称时,GlobalKeys 状态现在为空。

编辑:我注意到一个额外的尴尬行为是,当我填写表单 (FirstForm) 并在我运行应用程序时第一次按 Next 时,我得到了 null 错误。但是,在第一次运行该应用程序时,如果我在没有提交表单的情况下按 Next,验证器会工作,并向我显示填写输入的错误。

最佳答案

您需要将 key 传递给脚手架小部件,然后将设置上下文和状态。

class _MyHomePageState extends State<MyHomePage> {
GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey(); //so we can call snackbar from anywhere

...

Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey, //set state and context

...

//define method to call
void showInSnackBar(String value) {
_scaffoldKey.currentState.showSnackBar(new SnackBar(
content: new Text(value)
));
}

...

//Then you can call it
showInSnackBar("Proximity Alert, please distance yourself from the person or dangerous object close to you! This incident has been logged.");

关于Flutter GlobalKey 当前状态为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57209096/

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