飞镖:将地图转换为对象列表

时间:2019-07-27 17:36:49

标签: flutter dart

没有进行过几次Google搜索,但没有任何帮助。尝试做一些应该很简单的操作时,我会碰到一些错误。将诸如{2019-07-26 15:08:42.889861: 150, 2019-07-27 10:26:28.909330: 182}之类的映射转换为以下格式的对象列表:

class Weight {
  final DateTime date;
  final double weight;
  bool selected = false;

  Weight(this.date, this.weight);
}

我已经尝试过类似的操作:List<Weight> weightData = weights.map((key, value) => Weight(key, value));

显然,地图没有toList()方法。到目前为止,我还不喜欢飞镖中的地图。对象类型映射和映射函数之间的术语混淆。使故障排除在互联网上变得异常激烈。

9 个答案:

答案 0 :(得分:4)

根据上面的Richard Heap的评论,我会:

List<Weight> weightData =
  weightData.entries.map( (entry) => Weight(entry.key, entry.value)).toList();

别忘了调用toList,因为Dart的map返回一种Iterable。

答案 1 :(得分:4)

有时候类型转换会失败,您可以通过执行以下操作来强制执行:

List<Weight> weightData =
  weightData.entries.map<Weight>( (entry) => Weight(entry.key, entry.value)).toList();

我的项目中没有类型转换就无法工作的示例:

List<NetworkOption> networkOptions = response.data['data']['networks']
          .map<NetworkOption>((x) => NetworkOption.fromJson(x))
          .toList();

答案 2 :(得分:3)

entries对象上使用map属性

这将返回类型为List的{​​{1}}。

MapEntry<key,value>

答案 3 :(得分:2)

List<Weight> weightData = List();

weights.forEach((k,v) => weightData.add(Weight(k,v))); 

答案 4 :(得分:2)

详情

  • 颤振 1.26.0-18.0.pre.106

解决方案

<块引用>

/libs/extensions/map.dart

extension ListFromMap<Key, Element> on Map<Key, Element> {
  List<T> toList<T>(
          T Function(MapEntry<Key, Element> entry) getElement) =>
      entries.map(getElement).toList();
}

用法

import 'package:myApp/libs/extensions/map.dart';

final map = {'a': 1, 'b': 2};
print(map.toList((e) => e.value));
print(map.toList((e) => e.key));

答案 5 :(得分:1)

它非常简单,只需像这样初始化自定义对象的列表

List<CustomObject> list=[];
    for (int i = 0; i < map.length; i++) {
      CustomObject customObject= CustomObject(
       date:map[i]['key'],
       weight:map[i]['key']
      );
      list.add(CustomObject);
    }

希望对你有用,谢谢

答案 6 :(得分:1)

您也可以使用 git clone https://github.com/jscant/gnina_tensorflow.git cd gnina_tensorflow.git pip install -e . 集合来实现相同的目的。

Obtaining file:///C:/Users/82109/Desktop/gnina_tensorflow-master
Installing collected packages: gnina-tensorflow
  Running setup.py develop for gnina-tensorflow
Note: you may need to restart the kernel to use updated packages.
    ERROR: Command errored out with exit status 1:
     command: 'c:\anaconda3\envs\tfgpu\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\82109\\Desktop\\gnina_tensorflow-master\\setup.py'"'"'; __file__='"'"'C:\\Users\\82109\\Desktop\\gnina_tensorflow-master\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' develop --no-deps
         cwd: C:\Users\82109\Desktop\gnina_tensorflow-master\
    Complete output (60 lines):
    running develop
    running egg_info
    writing gnina_tensorflow.egg-info\PKG-INFO
    writing dependency_links to gnina_tensorflow.egg-info\dependency_links.txt
    writing top-level names to gnina_tensorflow.egg-info\top_level.txt
    reading manifest file 'gnina_tensorflow.egg-info\SOURCES.txt'
    writing manifest file 'gnina_tensorflow.egg-info\SOURCES.txt'
    running build_ext
    CMake Warning (dev) at CMakeLists.txt:1 (project):
      Policy CMP0048 is not set: project() command manages VERSION variables.
      Run "cmake --help-policy CMP0048" for policy details.  Use the cmake_policy
      command to set the policy and suppress this warning.

  The following variable(s) would be set to empty:

    CMAKE_PROJECT_VERSION
    CMAKE_PROJECT_VERSION_MAJOR
    CMAKE_PROJECT_VERSION_MINOR
    CMAKE_PROJECT_VERSION_PATCH
This warning is for project developers.  Use -Wno-dev to suppress it.

-- Selecting Windows SDK version 10.0.18362.0 to target Windows 10.0.19042.
-- pybind11 v2.6.0 dev1
-- Configuring done
-- Generating done
-- Build files have been written to: C:/Users/82109/Desktop/gnina_tensorflow-master/build/temp.win-amd64-3.8/Release
.NET Framework용 Microsoft (R) Build Engine 버전 16.8.3+39993bd9d
Copyright (C) Microsoft Corporation. All rights reserved.

cl : 명령줄 error D8021: '/Wextra' 숫자 인수가 잘못되었습니다. [C:\Users\82109\Desktop\gnina_tensorflow-master\build\temp.win-amd64-3.8\Release\cpp\gnina_tensorflow_cpp.vcxproj]
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\82109\Desktop\gnina_tensorflow-master\setup.py", line 91, in <module>
    setup(
  File "c:\anaconda3\envs\tfgpu\lib\distutils\core.py", line 148, in setup
    dist.run_commands()
  File "c:\anaconda3\envs\tfgpu\lib\distutils\dist.py", line 966, in run_commands
    self.run_command(cmd)
  File "c:\anaconda3\envs\tfgpu\lib\distutils\dist.py", line 985, in run_command
    cmd_obj.run()
  File "c:\anaconda3\envs\tfgpu\lib\site-packages\setuptools\command\develop.py", line 34, in run
    self.install_for_development()
  File "c:\anaconda3\envs\tfgpu\lib\site-packages\setuptools\command\develop.py", line 136, in install_for_development
    self.run_command('build_ext')
  File "c:\anaconda3\envs\tfgpu\lib\distutils\cmd.py", line 313, in run_command
    self.distribution.run_command(command)
  File "c:\anaconda3\envs\tfgpu\lib\distutils\dist.py", line 985, in run_command
    cmd_obj.run()
  File "C:\Users\82109\Desktop\gnina_tensorflow-master\setup.py", line 48, in run
    self.build_extension(ext)
  File "C:\Users\82109\Desktop\gnina_tensorflow-master\setup.py", line 84, in build_extension
    subprocess.check_call(['cmake', '--build', '.'] + build_args,
  File "c:\anaconda3\envs\tfgpu\lib\subprocess.py", line 364, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['cmake', '--build', '.', '--config', 'Release', '--', '/m']' returned non-zero exit status 1.
build_temp: build\temp.win-amd64-3.8\Release
extdir: C:\Users\82109\Desktop\gnina_tensorflow-master
python_exe: c:\anaconda3\envs\tfgpu\python.exe
cfg: Release
['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\\Users\\82109\\Desktop\\gnina_tensorflow-master', '-DPYTHON_EXECUTABLE=c:\\anaconda3\\envs\\tfgpu\\python.exe', '-DCMAKE_ARCHIVE_OUTPUT_DIRECTORY=C:\\Users\\82109\\Desktop\\gnina_tensorflow-master', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\\Users\\82109\\Desktop\\gnina_tensorflow-master', '-A', 'x64']


 ----------------------------------------
ERROR: Command errored out with exit status 1: 'c:\anaconda3\envs\tfgpu\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\82109\\Desktop\\gnina_tensorflow-master\\setup.py'"'"'; __file__='"'"'C:\\Users\\82109\\Desktop\\gnina_tensorflow-master\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' develop --no-deps Check the logs for full command output.
​

答案 7 :(得分:0)

Vidor的答案是正确的。无论如何,这对我来说都是有效的

      List<String> list = new List();
  userDetails.forEach((k, v) => list.add(userDetails[k].toString()));

答案 8 :(得分:0)

您可以这样做:

List<Weight> weightData = (weights as List ?? []).map((key, value) => Weight(key,value)).toList()

或者您可以尝试:

List<Weight> weightData = List.from(weights.map((key, value) => Weight(key, value)))