Flutter Access child function from its grand parent

Viewed 372

In my e-commerce admin cpanel app I have a very big form (product form) with lots of section one for title and description and price, one for sale one for colors and seizes and images etc. I divided it into smaller widget in separated classes and each of them has its own children widgets in another separated classes each child class has a ( onSave ) function which I need to trigger from the main form button located in the grand grand parent so how can I access all ( onSave ) functions from this parent

In this ( onSave ) functions I'm using provider pattern to pass the data I collect in each widget to a provider class and in there I can send the datd to the server

1 Answers

You can use the Form() widget and place your input fields in it as children. then you define a GlobalKey() and pass it to the form's key property. once you call the save method on the GlobalKey, all children widgets onSaved function will be called.

e.g.

import 'package:flutter/material.dart';

class MyScreen extends StatefulWidget {
  @override
  _MyScreenState createState() => _MyScreenState();
}

class _MyScreenState extends State<MyScreen> {
  final _formKey = GlobalKey<FormState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          children: [
            Form(
                key: _formKey,
                child: Column(
                  children: [
                    TextFormField(
                      decoration: InputDecoration(labelText: "Name"),
                      onSaved: (name) {
                        // do stuff
                      },
                    ),
                    TextFormField(
                      decoration: InputDecoration(labelText: "Category"),
                      onSaved: (category) {
                        // do stuff
                      },
                    ),
                  ],
                )),
            ElevatedButton(
              onPressed: () {
                _formKey.currentState.save();
              },
              child: Text("pressme"),
            )
          ],
        ),
      ),
    );
  }
}
Related