skip to Main Content

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

enter image description here

2

Answers


  1. You should move your _formKey definition outside _MyHomePageState and make it public:

    formKey = Global<FormState>()
    

    And then use the same formKey in both Form and ButonIslemi instead of instantiate a new key in ButonIslemi.

    Login or Signup to reply.
  2. You can send _formkey as parameter with button and use same key for button

    @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(_formKey),
            ElevatedButton(onPressed: sharedMessage, child: Text('share')),
          ],
        ),
      ),
    );
    }
    

    And here is button

    class ButonIslemi extends StatelessWidget {
       GlobalKey<FormState> _formKey;
       ButonIslemi(this._formKey, {super.key});
       @override
       Widget build(BuildContext context) {
          return ElevatedButton(onPressed: () {
           if(_formKey.currentState!.validate()) {
           print('işlem başarılı');
          }
        }, 
        child: Text('bas'));
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search