You can copy paste run each files below
Step 1: Use final keyForm = GlobalKey<EventFormFormState>();
Step 2: Pass keyForm
to EventFormForm(key: keyForm)
Step 3: In IconButton
call keyForm.currentState.saveForm();
IconButton(
icon: Icon(Icons.save),
onPressed: () {
keyForm.currentState.saveForm();
})
working demo
full code
main.dart
import 'package:flutter/material.dart';
import 'event_form.dart';
import 'event_form_form.dart';
void main() => runApp(MyApp());
final keyForm = GlobalKey<EventFormFormState>();
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: EventForm(),
);
}
}
event_form.dart
import 'package:flutter/material.dart';
import 'event_form_appbar.dart';
import 'event_form_body.dart';
class EventForm extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(appBar: EventFormAppBar(), body: EventFormBody());
}
}
event_form_appbar.dart
import 'package:flutter/material.dart';
import 'main.dart';
class EventFormAppBar extends PreferredSize {
@override
Widget build(BuildContext context) {
return AppBar(actions: <Widget>[
IconButton(
icon: Icon(Icons.save),
onPressed: () {
keyForm.currentState.saveForm();
})
]);
}
@override
get preferredSize => Size.fromHeight(50);
}
event_form_body.dart
import 'package:flutter/material.dart';
import 'main.dart';
import 'event_form_form.dart';
class EventFormBody extends StatelessWidget {
@override
Widget build(BuildContext context) {
return SafeArea(
child: SingleChildScrollView(
child: EventFormForm(key: keyForm),
),
);
}
}
event_form_form.dart
import 'package:flutter/material.dart';
class EventFormForm extends StatefulWidget {
EventFormForm({Key key}) : super(key: key);
@override
EventFormFormState createState() {
return EventFormFormState();
}
}
class EventFormFormState extends State<EventFormForm> {
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TextFormField(
validator: (value) {
if (value.isEmpty) {
return 'Please enter some text';
}
return null;
},
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: RaisedButton(
onPressed: () {
saveForm();
},
child: Text('Submit'),
),
),
],
),
);
}
void saveForm() {
print("execute save Form");
if (_formKey.currentState.validate()) {
// If the form is valid, display a Snackbar.
Scaffold.of(context)
.showSnackBar(SnackBar(content: Text('Processing Data')));
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…