簡體   English   中英

如何在 Dart 中使用 map 方法

[英]How to use the map methods in Dart

我正在嘗試 map 列表 api 收到的對象到我的 model 在 ZBB14127678960FAE97D87359 這是我正在接收的位置對象的 json

{
    "type": "success",
    "pick": [
        {
            "_id": "6023a3ec19d6ae001722c72a",
            "location": "{\"address_components\":[{\"long_name\":\"Jujube Drive\",\"short_name\":\"Jujube Dr\",\"types\":[\"route\"]},{\"long_name\":\"Lockhart\",\"short_name\":\"Lockhart\",\"types\":[\"locality\",\"political\"]},{\"long_name\":\"Orange County\",\"short_name\":\"Orange County\",\"types\":[\"administrative_area_level_2\",\"political\"]},{\"long_name\":\"Florida\",\"short_name\":\"FL\",\"types\":[\"administrative_area_level_1\",\"political\"]},{\"long_name\":\"United States\",\"short_name\":\"US\",\"types\":[\"country\",\"political\"]},{\"long_name\":\"32810\",\"short_name\":\"32810\",\"types\":[\"postal_code\"]}],\"formatted_address\":\"Jujube Dr, Lockhart, FL 32810, USA\",\"geometry\":{\"location\":{\"lat\":28.6305958,\"lng\":-81.4201272}},\"place_id\":\"EiJKdWp1YmUgRHIsIExvY2toYXJ0LCBGTCAzMjgxMCwgVVNBIi4qLAoUChIJbYeMktZw54gRrNCvH7dMCb4SFAoSCYuShqblcOeIETWEcayC8atP\",\"html_attributions\":[]}"
        }
    ],
    "drop": []
}

所以在下面的方法中,我知道請求是否成功,然后我只得到pick列表。

    if(data['type']=='success'){
      if(type==LocationType.Pickup){
        List pickupLocations = data['pick'];
        print(pickupLocations.length);
        return pickupLocations.map(yieldUserLocation);
      }else{
        List dropLocations = data['drop'];
        return dropLocations.map(yieldUserLocation);
      }
    }

由於我想返回UserLocations列表(我的自定義模型),我嘗試將 map 列表放入此方法

   yieldUserLocation(List locations){
    print('I got here');
    try{
      return locations.map((location) {
        return UserLocation(
          id:location['_id'],
          longitude: location[''],
          latitude: location[''],
          location: location[''],
        );
      }).toList();
    }catch(e){
      print(e.toString());
    }
  }

更新

這是使用未來getUserLocations()的構建器

       FutureBuilder<List<UserLocation>>(
        future: UserLocationService().getUserLocations(LocationType.Pickup),
        builder: (context, snapshot) {
            List<UserLocation> locations = snapshot.data;
            bool isLocations = snapshot.hasData;
            print(locations);
            return Container(
              margin: pageMargin(context),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(height: screenHeight(context)*0.02,),
                  !noLocations?SizedBox(
                    height: 200,
                    child: ListView.builder(
                      itemCount: locations.length,
                      itemBuilder: (context,index){
                          return  ListTile(
                            title: Text(locations[index].id),
                            subtitle: Text('3km'),
                            trailing: Icon(Icons.delete,color: themeColor),
                          );
                      },
                    ),
                  ):
                  Center(
                    child: Text('No saved locations',style: TextStyle(fontWeight: FontWeight.bold,color: Colors.grey[800]),),
                  ),
                ],
              ),
            );
        }
      ),

print(locations); 保留為 null。

出於某種原因,可能是因為我做錯了,我無法獲得項目列表,事實上 function 返回 null。 我注意到它甚至不打印消息print('I got here'); 在控制台中。 我哪里做錯了?

重構后這對我有用

    if(data['type']=='success'){
      if(type==LocationType.Pickup){
        List pickupLocations = data['pick'];
        return pickupLocations.map((location) {
          print(location['_id']);
          return UserLocation(
            id:location['_id'],
            longitude: '',
            latitude: '',
            location: location['location'],
          );
        }).toList();
      }else{
        List dropLocations = data['drop'];
        return dropLocations.map((location) {
          print(location['_id']);
          return UserLocation(
            id:location['_id'],
            longitude: '',
            latitude: '',
            location: location['location'],
          );
        }).toList();
      }
    }else{
      return [];
    }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM