'Parse string to widget in Flutter

I want to parse the following string to its equivalent Flutter widgets:

String fetchedFromServer = '''
Container(
   child: Text("Hello")
)
''';

I want to receive layouts from web server and parse them to real widgets.

How can I do that in Dart/Flutter.



Solution 1:[1]

You're probably going to have to create the parsing and rendering mechanism yourself, as I don't think Flutter has any support for server-side rendering (other than maybe with Flutter Web, though I haven't heard any news there).

Furthermore, you will probably want to return the layout data in JSON or another data format. For starters, it will be much easier to parse and process. Beyond that, though, if you wanted to render UI based on raw Dart you would have to effectively set up your app to be able to run arbitrary Dart code from a string, which is not only very difficult to manage in Dart/Flutter but also opens your up to an untold number of potential security issues.

Back on topic, suppose you have the following UI data:

{
  "class": "Container",
  "child": {
    "class": "Text",
    "value": "Hello"
  }
}

In your app, you could parse this like so:

Widget fetchUI(url) {
  // TODO: Make network call to get response
  final data = json.decode(response.body);
  return parseWidget(data);
}

Widget parseWidget(data) {
  switch(data['class']) {
    case 'Container':
      return Container(
        child: parseWidget(data['child']),
      );
    case 'Text':
      return Text(data['value']);
  }
  return null;
}

Solution 2:[2]

One option would be to use this package

https://pub.dev/packages/flutter_widget_from_html

and store the layouts you want as HTML. Keep in mind it would only be able to support basic widgets and layouts, but you wouldn't have to write the parser yourself.

Solution 3:[3]

Actually there is a new project that aims to do exactly what you want. I have not tried it myself, but it seems to be working. Another benefit is that it does not render html or any other markup language, but Json to native Flutter widgets.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abion47
Solution 2 Emmett Deen
Solution 3 Focus Android