我正在进行验证过程,但我想在不同的页面之间进行验证。如何使用formKey或其他解决方案在另一个页面上执行验证过程?我得到了一个空错误,如何摆脱它?
我的主文件在下面
import 'package:flutter/material.dart';
import 'package:intl_flutter_deneme/buton.dart';
import 'package:intl_phone_number_input/intl_phone_number_input.dart';
import 'package:mask_text_input_formatter/mask_text_input_formatter.dart';
import 'package:share_plus/share_plus.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(primarySwatch: Colors.amber),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
TextEditingController phoneController = TextEditingController();
bool isButtonActive = false;
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('phone number settings'),
),
body: Center(
child: Column(
children: [
Form(
key: _formKey,
child: InternationalPhoneNumberInput(
countries: ['TR'],
onInputChanged: (PhoneNumber number) {
print(number.phoneNumber);
},
maxLength: 13,
hintText: '5## ### ## ##',
validator: (deger) {
if(deger!.isEmpty && deger.length < 13) {
return 'doğru şekilde numara gir';
}return null;
},
spaceBetweenSelectorAndTextField: 0,
inputDecoration: InputDecoration(),
textFieldController: phoneController,
),
),
ButonIslemi(),
ElevatedButton(
onPressed: sharedMessage, child: Text('share')),
],
),
),
);
}
void sharedMessage() {
String message = 'https://www.instagram.com/atakansever_/';
Share.share(message);
}
}
按下按钮时执行验证的部分如下所示
import 'package:flutter/material.dart';
import 'package:intl_flutter_deneme/main.dart';
class ButonIslemi extends StatelessWidget {
ButonIslemi({super.key});
final formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return ElevatedButton(onPressed: () {
if(formKey.currentState!.validate()) {
print('işlem başarılı');
}
}, child: Text('bas'));
}
}
我按下按钮时得到的错误如下
2条答案
按热度按时间z18hc3ub1#
您可以将_formkey作为参数与button一起发送,并将相同的键用于button
这是巴顿
fnvucqvd2#
您应该将_formKey定义移到
_MyHomePageState
之外并使其公开:然后在
Form
和ButonIslemi
中使用相同的formKey
,而不是在ButonIslemi
中示例化一个新的密钥。