Skip to content

Instantly share code, notes, and snippets.

@rydmike
Last active March 26, 2020 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rydmike/a46d59f1a18e8aeeb6b8bfdc55308858 to your computer and use it in GitHub Desktop.
Save rydmike/a46d59f1a18e8aeeb6b8bfdc55308858 to your computer and use it in GitHub Desktop.
A Flutter example of how to make a Widget member value have a default value, while being extension/compose and null safe. Part of this Twitter discussion: https://twitter.com/RydMike/status/1243200280809930753
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
home: Scaffold(
body: SuperWidget(
child: Text('This is supposed to have a red background'),
),
),
),
);
}
// -----------------------------------------------------------------------------
// This would be in your "super_widget.dart" file if you want to keep it separate
/// A widget that uses [SomeBaseWidget] but still expose some customization
// As is, it is useless – it's just for the sake of example
class SuperWidget extends SomeBaseWidget {
const SuperWidget({Key key, this.color, this.child}) : super(key: key);
final Color color;
final Widget child;
@override
Widget build(BuildContext context) {
return SomeBaseWidget(
// NOTE: This color has default value, is extension and null safe
color: color,
child: child,
);
}
}
// -----------------------------------------------------------------------------
// This would be in your "some_base_widget.dart" file
/// [SomeBaseWidget] defaults to red color background
const _kDefaultColor = Colors.red;
/// A customizable low level widget with some default value
class SomeBaseWidget extends StatelessWidget {
const SomeBaseWidget({
Key key,
this.color = _kDefaultColor,
this.child,
}) : super(key: key);
/// Color of the [SomeBaseWidget]
final Color color;
/// The child of [SomeBaseWidget]
final Widget child;
@override
Widget build(BuildContext context) {
// If null is passed we set it back to the default value, this is now an
// implementation null safety and extension/composition safety detail
final color = this.color ?? _kDefaultColor;
return Container(
color: color,
alignment: Alignment.center,
child: child,
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment