Created
December 18, 2023 20:19
-
-
Save rodydavis/00e4d368c1baf3085916fb41ef46fbef to your computer and use it in GitHub Desktop.
Flutter RFW Helper Widget
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'; | |
import 'package:rfw/formats.dart'; | |
import 'package:rfw/rfw.dart'; | |
class Rfw extends StatefulWidget { | |
const Rfw({ | |
super.key, | |
required this.source, | |
this.data = const {}, | |
}); | |
final String source; | |
final Map<String, dynamic> data; | |
@override | |
State<Rfw> createState() => _RfwState(); | |
} | |
class _RfwState extends State<Rfw> { | |
bool loading = false; | |
final _runtime = Runtime(); | |
final _data = DynamicContent(); | |
String? _lastUi; | |
Map<String, dynamic>? _lastArgs; | |
@override | |
void initState() { | |
super.initState(); | |
_runtime.update( | |
const LibraryName(<String>['core']), | |
createCoreWidgets(), | |
); | |
_runtime.update( | |
const LibraryName(<String>['material']), | |
createMaterialWidgets(), | |
); | |
onRfw(widget.source, widget.data); | |
} | |
static const mainLibrary = LibraryName(<String>['main']); | |
RemoteWidgetLibrary? _remoteWidget; | |
void setLoading(bool value) { | |
if (mounted) { | |
setState(() { | |
loading = value; | |
}); | |
} | |
} | |
void onRfw(String result, Map<String, dynamic> args) { | |
final isNew = _lastUi == null && _lastArgs == null; | |
if (_lastUi != result) { | |
if (result.trim().isEmpty) return; | |
_remoteWidget = parseLibraryFile(result); | |
_runtime.update(mainLibrary, _remoteWidget!); | |
_lastUi = result; | |
} | |
if (_lastArgs != args) { | |
_data.updateAll(args); | |
_lastArgs = args; | |
} | |
if (!isNew && mounted) setState(() {}); | |
} | |
@override | |
void didUpdateWidget(covariant Rfw oldWidget) { | |
if (oldWidget.source != widget.source || oldWidget.data != widget.data) { | |
onRfw(widget.source, widget.data); | |
} | |
super.didUpdateWidget(oldWidget); | |
} | |
@override | |
Widget build(BuildContext context) { | |
if (_remoteWidget == null) { | |
return const Center(child: CircularProgressIndicator()); | |
} | |
return RemoteWidget( | |
runtime: _runtime, | |
data: _data, | |
widget: const FullyQualifiedWidgetName(mainLibrary, 'root'), | |
onEvent: (name, arguments) => onEvent(context, name, arguments), | |
); | |
} | |
void onEvent( | |
BuildContext context, | |
String name, | |
Map<String, dynamic>? arguments, | |
) { | |
debugPrint('user triggered event "$name" with data: $arguments'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment