Created
April 3, 2019 22:02
-
-
Save slightfoot/d66ab662c8dcc25b62fdda8009c4c8a9 to your computer and use it in GitHub Desktop.
Example of Dynamic Widget Creation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
abstract class Event {} | |
class TTimeEntryCreated extends Event {} | |
class TTimeEntryEdited extends Event {} | |
class TTimeEntryDeleted extends Event {} | |
class TStripeChargeCreated extends Event {} | |
typedef EventWidgetBuilder = Widget Function(BuildContext context, Event event); | |
class Entry { | |
Event sourceEvent; | |
String memo; | |
} | |
class EntryWidget extends StatelessWidget { | |
const EntryWidget({ | |
Key key, | |
@required this.entry, | |
}) : super(key: key); | |
final Entry entry; | |
@override | |
Widget build(BuildContext context) { | |
final event = entry.sourceEvent; | |
if (event == null) { | |
return Text(entry.memo); | |
} else { | |
final builder = _lookup[event.runtimeType]; | |
return builder?.call(context, event) ?? Text('Unknown'); | |
} | |
} | |
static const _lookup = <Type, EventWidgetBuilder>{ | |
TTimeEntryCreated: _buildTimeEntryCreated, | |
TTimeEntryEdited: _buildTimeEntryEdited, | |
TTimeEntryDeleted: _buildTimeEntryDeleted, | |
TStripeChargeCreated: _buildStripeChargeCreated, | |
}; | |
static Widget _buildTimeEntryCreated(BuildContext context, Event event) { | |
return Text('TimeEntry Created'); | |
} | |
static Widget _buildTimeEntryEdited(BuildContext context, Event event) { | |
return Text('TimeEntry Edited'); | |
} | |
static Widget _buildTimeEntryDeleted(BuildContext context, Event event) { | |
return Text('TimeEntry Deleted'); | |
} | |
static Widget _buildStripeChargeCreated(BuildContext context, Event event) { | |
return Text('Stripe Charge Created'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment