这是flutter代码,toListString=map["playList"] as List<String>; _playList=toListString.toList<String>();map["playList"]是_GrowableList。我想把map["playList"] 转为List<String>可我写错了,第一句就结束了运行。你能帮我改改吗
时间: 2023-03-29 17:04:45 浏览: 64
当然可以帮您改改。您可以尝试以下代码:
List<String> toListString = List<String>.from(map["playList"]);
_playList = toListString.toList();
这样应该就可以将_GrowableList转换为List<String>了。
相关问题
flutter List<dynamic>转 Map<String, dynamic>
可以使用`asMap()`方法将`List<dynamic>`转换为`Map<String, dynamic>`。以下是一个示例代码:
```dart
List<dynamic> list = [
{'name': 'John', 'age': 25},
{'name': 'Jane', 'age': 30},
];
Map<String, dynamic> map = Map.fromIterable(
list.asMap().keys,
key: (index) => index.toString(),
value: (index) => list[index],
);
print(map);
```
输出结果为:
```dart
{
'0': {'name': 'John', 'age': 25},
'1': {'name': 'Jane', 'age': 30}
}
```
这个示例中,我们首先使用`asMap()`将列表转换为索引-值对的映射。然后,使用`Map.fromIterable()`方法将索引作为字符串键,对应的值作为映射的值。最终得到一个`Map<String, dynamic>`对象。
flutter List<String> switchType = [] 转为fromJson
假设你要将以下JSON字符串转换为Dart对象:
```
{
"switchType": ["type1", "type2", "type3"]
}
```
你可以定义一个包含 `fromJson` 工厂方法的Dart类来实现转换。例如:
```dart
class Switches {
List<String> switchType;
Switches({this.switchType});
factory Switches.fromJson(Map<String, dynamic> json) {
return Switches(
switchType: List<String>.from(json['switchType']),
);
}
}
```
然后,你可以使用 `json.decode` 方法将JSON字符串转换为 `Map` 对象,再使用 `fromJson` 工厂方法将 `Map` 转换为 `Switches` 对象。例如:
```dart
String jsonString = '{"switchType":["type1","type2","type3"]}';
Map<String, dynamic> jsonMap = json.decode(jsonString);
Switches switches = Switches.fromJson(jsonMap);
print(switches.switchType); // ["type1", "type2", "type3"]
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)