I have a page with a form. Once the user clicks on Save, it should display a SnackBar. The save button is in a separate custom AppBar widget (in a separate file) and it has 2 functions that is sent from the page with the form. The AppBar is separated for reusable purposes.
I have tried to use the Builder method but it doesn't work. Then I used the Global Key method and it won't give me an error, but still no SnackBar.
import 'package:flutter/material.dart';
import '../models/author.dart';
import '../widgets/edit_app_bar.dart';
class AuthorEditPage extends StatefulWidget {
static const PAGE_TITLE = 'Edit Author';
static const ROUTE_NAME = '/author-edit';
@override
_AuthorEditPageState createState() => _AuthorEditPageState();
}
class _AuthorEditPageState extends State<AuthorEditPage> {
@override
Widget build(BuildContext context) {
final _operation = ModalRoute.of(context).settings.arguments as String;
final GlobalKey<ScaffoldState> _scaffoldKey =
new GlobalKey<ScaffoldState>();
Author _initialize() {
return Author(
id: null,
name: 'Test',
nameOther: null,
facebook: null,
website: null,
lastUpdated: DateTime.now().toIso8601String(),
);
}
void _displaySnackBar(Author author) {
_scaffoldKey.currentState.showSnackBar(
SnackBar(
content: Text(
'Author: ${author.name} added',
),
),
);
}
return Scaffold(
key: _scaffoldKey,
appBar: EditAppBar(
title: AuthorEditPage.PAGE_TITLE,
saveAndAddNew: () async {
Author author = _initialize();
bool result = await author.createUpdateDelete(_operation);
if (result) {
_displaySnackBar(author);
setState(() {});
}
},
save: () async {
Author author = _initialize();
bool result = await author.createUpdateDelete(_operation);
if (result) {
_displaySnackBar(author);
Navigator.of(context).pop();
}
},
),
body: null,
);
}
}
The Custom AppBar
import 'package:flutter/material.dart';
class EditAppBar extends StatelessWidget with PreferredSizeWidget {
EditAppBar({
Key key,
@required this.title,
@required this.saveAndAddNew,
@required this.save,
}) : super(key: key);
final String title;
final Function saveAndAddNew;
final Function save;
@override
Widget build(BuildContext context) {
return AppBar(
title: Text(
title,
),
actions: <Widget>[
IconButton(
icon: Icon(
Icons.add,
),
onPressed: saveAndAddNew,
),
IconButton(
icon: Icon(
Icons.save,
),
onPressed: save,
),
],
);
}
@override
Size get preferredSize => Size.fromHeight(kToolbarHeight);
}
Any help/guidance is highly appreciated!