6

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.

3 Answers 3

7

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

good solution, thankyou. though there is a package related to your answer, pub.dev/packages/dynamic_widget, but in the end; its a pain to convert complex flutter widget-layouts to json string
0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.