将字符串解析为Flutter中的小部件 [英] Parse string to widget in Flutter

查看:32
本文介绍了将字符串解析为Flutter中的小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将以下字符串解析为其等效的Flutter小部件:

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

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

我想从Web服务器接收布局并将其解析为真实的小部件.

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

如何在Dart/Flutter中做到这一点.

How can I do that in Dart/Flutter.

推荐答案

您可能必须自己创建解析和渲染机制,因为我不认为Flutter对服务器端渲染有任何支持(其他比起Flutter Web,虽然我还没有听到任何消息.

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).

此外,您可能希望以JSON或其他数据格式返回布局数据.对于初学者来说,解析和处理会容易得多.但是,除此之外,如果您想基于原始Dart呈现UI,则必须有效地设置您的应用程序,以便能够从字符串中运行任意Dart代码,这不仅在Dart/Flutter中管理起来非常困难,而且为您打开了无数潜在的安全隐患.

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.

回到主题,假设您具有以下UI数据:

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;
}

这篇关于将字符串解析为Flutter中的小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆