I’m doing a validation process, but I want to do it between different pages. How can I perform the validate process on another page using formKey or another solution? I’m getting a null error, how do I get rid of it?
my main file is below
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);
}
}
The part that performs the validation when the button is pressed is below
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'));
}
}
The error I get when pressing the button is as follows
2
Answers
You should move your _formKey definition outside
_MyHomePageState
and make it public:And then use the same
formKey
in bothForm
andButonIslemi
instead of instantiate a new key inButonIslemi
.You can send _formkey as parameter with button and use same key for button
And here is button