简体   繁体   English

Flutter如何在List map中映射一个完整的Future对象

[英]Flutter how to map a completed Future object in List map

Future<List<Future<News>>> getNewsList(skipItems) async {
    final response = await http.get(
        'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty');

    if (response.statusCode == 200) {
      // If the call to the server was successful, parse the JSON
      var responseNewsList = json.decode(response.body);
      newsList = responseNewsList as List;
      var resNewsList = (responseNewsList as List)
          .skip(skipItems)
          .take(20)
          .map((id) =>  this.fetchNewsDetails(id))
          .toList();

      return resNewsList;
    } else {
      // If that call was not successful, throw an error.
      throw Exception('Failed to load post');
    }
}

Future<News> fetchNewsDetails(id) async {
    final response = await http.get(
        'https://hacker-news.firebaseio.com/v0/item/$id.json?print=pretty');

    if (response.statusCode == 200) {
      // If the call to the server was successful, parse the JSON
      return News.fromJson(json.decode(response.body));
    } else {
      // If that call was not successful, throw an error.
      throw Exception('Failed to load post');
    }
}

So as the code you can see that I try to get a list of top stories post but the response only return me a list of ids, so I will need call another api to get the post detail, in the way above I will need to use twice Future Builder for display the content, the way works but is there anyway for me to wait the response back and have the post result in the mapping function?因此,作为代码,您可以看到我尝试获取头条新闻列表,但响应仅返回一个 id 列表,因此我需要调用另一个 api 来获取帖子详细信息,我需要按照上面的方式使用两次Future Builder来显示内容,方法可行,但无论如何让我等待响应并在映射函数中获得发布结果?

I assume you want我假设你想要

await Stream.fromIterable((responseNewsList as List)
      .skip(skipItems)
      .take(20))
      .asyncMap((id) =>  this.fetchNewsDetails(id))
      .toList();

https://api.dartlang.org/stable/2.1.0/dart-async/Stream/asyncMap.html https://api.dartlang.org/stable/2.1.0/dart-async/Stream/asyncMap.html

An alternative approach to Günter's is to replace the manual creation of a stream and make it more explicit you actually just want the completed Futures instead: Günter 的另一种方法是替换手动创建流并使其更加明确,您实际上只想要完整的 Futures:

await Future.wait((responseNewsList as List)
    .skip(skipItems)
    .take(20)
    .map((id) => fetchNewsDetails(id)))
  ).toList();

如何使用字符串和列表的 Map<object> 在 flutter<div id="text_translate"><p> 我做了几次谷歌搜索,没有任何帮助。 在尝试做一些应该很简单的事情时,我一直在努力解决一些错误。 在使用 OdooApi 连接到 Odoo 时从字典列表中检索数据,以便在列表视图或任何合适的设计中显示它:</p><p> 1 - 创建一个home_page.dart包含一个文本字段,其中添加id作为输入</p><pre>. . child: TextField( decoration: new InputDecoration( focusedBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.red)), enabledBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.redAccent) ), filled: false, //fillColor: Color(0xFFBB162B), hintText: "Numéro d'OR", ), onChanged: (text){ num_or = text; }, ), ), Expanded( child: Center( child: RawMaterialButton( onPressed: () {_navigateAndDisplayCheckScreen(num_or);}, shape: const StadiumBorder(), fillColor: AppColor.secondaryColor, child: const Padding( padding: EdgeInsets.symmetric(vertical: 12.0, horizontal: 24.0), child: Text( "Vérifier", style: TextStyle( color: Colors.white, fontSize: 26.0, fontWeight: FontWeight.bold, ), . . Future&lt;void&gt; _navigateAndDisplayCheckScreen(num_or) async { final result = await Navigator.of(context).push( MaterialPageRoute(builder: (context) =&gt; CheckScreen( num_or: num_or)), ); }</pre><p> 2 - 创建check_screen.dart到:</p><pre> class CheckScreen extends StatefulWidget { // CheckScreen({key, num_or}): super(key: key); String id; CheckScreen({this.id}); @override _CheckScreenState createState() =&gt; _CheckScreenState(); } class _CheckScreenState extends State&lt;CheckScreen&gt; { var dt; String id; _CheckScreenState({this.id}); _getDataFromServer(id) async { client.authenticate(email, password, database).then((auth) async { if (auth.isSuccess) { OdooResponse result = await client.searchRead('account.invoice', [ ['id', '=', id] ], [ 'id', 'name', 'number', 'origin' ]); var dt = result.getResult()['records']; print("i'm dt $dt"); print("i'm id: $id"); setState(() { c = dt; });} else { print("Login Gagal"); } }); } @override void initState() { super.initState(); _getDataFromServer(widget.num_or); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Pick an option'), ), body: Center( child: Text(c), ), ); }</pre><p> Output:</p><pre> data = [{id:10, name: Imad, number: 1344,origin: OR00348}]</pre><p> 而且,我得到:</p><pre> he method '[]' was called on null. Receiver: null Tried calling: [](0)</pre></div></object> - how to work with Map of String and List<Object> in flutter

暂无
暂无

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

相关问题 Flutter map 列表成 object - Flutter map a list into object Map列表<future<object> &gt; 进入列表<object><div id="text_translate"><p>我有一个</p><pre class="lang-dart prettyprint-override">List&lt;Future&lt;int&gt;&gt;</pre><p> 我如何将其转换为</p><pre class="lang-dart prettyprint-override">List&lt;int&gt;</pre> </div></object></future<object> - Map List<Future<Object>> into List<Object> 如何使用字符串和列表的 Map<object> 在 flutter<div id="text_translate"><p> 我做了几次谷歌搜索,没有任何帮助。 在尝试做一些应该很简单的事情时,我一直在努力解决一些错误。 在使用 OdooApi 连接到 Odoo 时从字典列表中检索数据,以便在列表视图或任何合适的设计中显示它:</p><p> 1 - 创建一个home_page.dart包含一个文本字段,其中添加id作为输入</p><pre>. . child: TextField( decoration: new InputDecoration( focusedBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.red)), enabledBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.redAccent) ), filled: false, //fillColor: Color(0xFFBB162B), hintText: "Numéro d'OR", ), onChanged: (text){ num_or = text; }, ), ), Expanded( child: Center( child: RawMaterialButton( onPressed: () {_navigateAndDisplayCheckScreen(num_or);}, shape: const StadiumBorder(), fillColor: AppColor.secondaryColor, child: const Padding( padding: EdgeInsets.symmetric(vertical: 12.0, horizontal: 24.0), child: Text( "Vérifier", style: TextStyle( color: Colors.white, fontSize: 26.0, fontWeight: FontWeight.bold, ), . . Future&lt;void&gt; _navigateAndDisplayCheckScreen(num_or) async { final result = await Navigator.of(context).push( MaterialPageRoute(builder: (context) =&gt; CheckScreen( num_or: num_or)), ); }</pre><p> 2 - 创建check_screen.dart到:</p><pre> class CheckScreen extends StatefulWidget { // CheckScreen({key, num_or}): super(key: key); String id; CheckScreen({this.id}); @override _CheckScreenState createState() =&gt; _CheckScreenState(); } class _CheckScreenState extends State&lt;CheckScreen&gt; { var dt; String id; _CheckScreenState({this.id}); _getDataFromServer(id) async { client.authenticate(email, password, database).then((auth) async { if (auth.isSuccess) { OdooResponse result = await client.searchRead('account.invoice', [ ['id', '=', id] ], [ 'id', 'name', 'number', 'origin' ]); var dt = result.getResult()['records']; print("i'm dt $dt"); print("i'm id: $id"); setState(() { c = dt; });} else { print("Login Gagal"); } }); } @override void initState() { super.initState(); _getDataFromServer(widget.num_or); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Pick an option'), ), body: Center( child: Text(c), ), ); }</pre><p> Output:</p><pre> data = [{id:10, name: Imad, number: 1344,origin: OR00348}]</pre><p> 而且,我得到:</p><pre> he method '[]' was called on null. Receiver: null Tried calling: [](0)</pre></div></object> - how to work with Map of String and List<Object> in flutter Flutter 如何从 Future Function 访问 map - Flutter how to access the map from Future Function Flutter:如何转换 Future<dynamic> 到地图 - Flutter: How to convert Future<dynamic> to Map 如何用Dart语言将Future <List <Map>转换为List <Map>? - How to transform Future<List<Map> to List<Map> in Dart language? Flutter - 输入“未来”<dynamic> ' 不是类型 'List 的子类型<map<string, dynamic> >' </map<string,></dynamic> - Flutter - type 'Future<dynamic>' is not a subtype of type 'List<Map<String, dynamic>>' Flutter 从 QuerySnapshot 转换为 Future <list<map<dynamic, dynamic> >> </list<map<dynamic,> - Flutter Convert from QuerySnapshot to a Future <List<Map<dynamic, dynamic>>> 在 Flutter 中迭代未来 Map - Iterate through a Future Map in Flutter 如何 map 响应 Map<string, object> 在 flutter</string,> - how to map response to Map<String, Object> in flutter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM