简体   繁体   English

Flutter:从 http 调用中捕获 Future 响应作为普通列表

[英]Flutter : Capture the Future response from a http call as a normal List

I am trying to make my previously static app, dynamic by making calls to the backend server.我试图通过调用后端服务器来使我以前的静态应用程序变得动态。

This is what my service looks like这就是我的服务的样子

String _url = "http://localhost:19013/template/listAll";

Future<List<TemplateInfoModel>> fetchTemplates() async {
  final response =
  await http.get(_url);
  print(response.statusCode);

  if (response.statusCode == 200) {
    // If the call to the server was successful, parse the JSON
    Iterable l = json.decode(response.body);
    List<TemplateInfoModel> templates = l.map((i) => TemplateInfoModel.fromJson(i)).toList();
    return templates;
  } else {
  // If that call was not successful, throw an error.
  throw Exception('Failed to load post');
  }
}

And my model looks like this :我的模型看起来像这样:

class TemplateInfoModel {
  final String templateId;
  final String messageTag;
  final String message;
  final String messageType;


  TemplateInfoModel({this.templateId, this.messageTag, this.message,
    this.messageType});

  factory TemplateInfoModel.fromJson(Map<String, dynamic> json) {
    return TemplateInfoModel ( templateId: json['templateId'], messageTag : json['messsageTag'], message : json ['message'] , messageType : json['messageType']);
  }

}

I have a utils method within which I am capturing the http request/response data;我有一个 utils 方法,可以在其中捕获 http 请求/响应数据; which would then use that to create a DropDown Widget ( or display it within a text)然后将使用它来创建一个 DropDown 小部件(或在文本中显示它)

My earlier dummy data was a list;我之前的虚拟数据是一个列表; I am wondering how best I can convert this Future> to List我想知道如何最好地将此 Future> 转换为 List

class SMSTemplatingEngine {

    var _SMSTemplate; //TODO this becomes a Future<List<TemplateInfoModels>>
   // TemplateInfoService _templateInfoService;

    SMSTemplatingEngine(){
      _SMSTemplate=fetchTemplates();
    }

//  var _SMSTemplate = {
//    'Reminder':
//        'Reminder : We’re excited to launch a new feature on our platform that will revolutionize your Facebook marketing and triple your ROI. Visit url.com to learn more',
//    'New Message':
//        'New Message: We’re excited to launch a new feature on our platform that will revolutionize your Facebook marketing and triple your ROI. Visit url.com to learn more',
//    'Connecting Again':
//        'Connecting Again : We’re excited to launch a new feature on our platform that will revolutionize your Facebook marketing and triple your ROI. Visit url.com to learn more',
//  };

  List<String> getKeys(){
    List<String> smsKeys = new List();
    for ( var key in _SMSTemplate.keys)
      smsKeys.add(key);
    return smsKeys;
  }

  String getValuePerKey(String key){
    return _SMSTemplate['${key}'];
  }


}

PS I have looked at some posts but I was completely bowled over since I am a Flutter Newbie. PS 我看过一些帖子,但由于我是 Flutter 新手,我完全被打倒了。

Is there an easier way for this to happen.有没有更简单的方法来实现这一点。

Thanks,谢谢,

The widget which would display the content from the http call将显示来自 http 调用的内容的小部件

   var templateMessagesDropDown = new DropdownButton<String>(
      onChanged: (String newValue) {
        setState(() {
          templateMsgKey = newValue;
          print("Selcted : ${templateMsgKey.toString()} ");
        });
      },
      // value: _defaultTemplateValue,
      style: textStyle,
      //elevation: 1,
      hint: Text("Please choose a template"),
      isExpanded: true,
      //
      items: smsEngine.getKeys().map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
    );

I am wondering how best I can convert this Future to List我想知道如何最好地将此 Future 转换为 List

Future<List<TemplateInfoModel>> fetchTemplates() should return a List that you're expecting. Future<List<TemplateInfoModel>> fetchTemplates()应该返回您期望的列表。 You may want to consider either using FutureBuilder or StreamBuilder to update the UI elements on your screen.您可能需要考虑使用 FutureBuilder 或 StreamBuilder 来更新屏幕上的 UI 元素。 Or if you're not keen on using either of those, you can just call the Future and update the List on your current screen.或者,如果您不喜欢使用其中任何一个,您可以调用 Future 并更新当前屏幕上的列表。

List<TemplateInfoModel> _listTemplateInfoModel = [];
...

fetchTemplates().then((value){
  setState((){
    _listTemplateInfoModel = value;
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM