So, I am learning about anonymous functions in dart which I know helps to reduce and simplify the code when passing a function as an argument to another function. Now, what I want to know is how exactly is this used in building an application using flutter. I am here seeking some practical implementation in actual flutter applications.
CodePudding user response:
Let's have a look at this example:
final updatedUser = repository.updateUser(
one rror: () {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('User could not be updated'),
));
},
onSuccess: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('User updated'),
),
);
},
);
repository.dart
Future<User> updateUser({
void Function()? onSuccess,
void Function()? one rror,
}) async {
final response = await api.updateUser();
if (response.statusCode == 200) {
onSuccess?.call();
}
if (response.statusCode! < 200 || response.statusCode! > 300) {
one rror?.call();
}
return response.data!
}
The repository shouldn't know about anything about a BuildContext
so we can't show a snackbar right in it.
To show them anyway we can do this in callbacks, using the context of the calling widget.
CodePudding user response:
Imagine you wanted to implement a CustomButton
to reuse it across your entire app. In that case, it typically makes sense for it to return a callback function and handle the event where the button is being used. To do so, you pass an onPressed
function to the button, which will be invoked by the button's internal onPressed
function.
class CustomButton extends StatelessWidget {
const CustomButton({
required this.onPressed,
required this.title,
});
final void Function() onPressed;
final String title;
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: onPressed,
child: Text(title),
);
}
}
Using it:
CustomButton(
onPressed: () => Navigator.pushNamed(context, '/pageTwo'),
title: 'Navigate',
)
The CustomButton
can now push
, pop
, or do all kinds of things. It is way more flexible than if you implemented a button without a callback function:
class ForwardButton extends StatelessWidget {
const ForwardButton({
required this.destination,
required this.title,
});
final String destination;
final String title;
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () => Navigator.pushNamed(context, destination),
child: Text(title),
);
}
}
ForwardButton(
destination: '/pageTwo',
title: 'Navigate',
)
If you wanted the ForwardButton
to do things other than Navigator.pushNamed
, you'd need to add more logic or arguments to the constructor, and it'll quickly become messy.