未处理的异常:类型 'List<dynamic>' 不是类型 'Map<String, dynamic>' 的子类型

Posted

技术标签:

【中文标题】未处理的异常:类型 \'List<dynamic>\' 不是类型 \'Map<String, dynamic>\' 的子类型【英文标题】:Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'未处理的异常:类型 'List<dynamic>' 不是类型 'Map<String, dynamic>' 的子类型 【发布时间】:2019-09-26 13:45:51 【问题描述】:

更新:感谢@Rjulcaa 的回答我的地图现在是一个列表,但是该列表没有显示在 UI 上。我认为我需要使用 FutureBuilder 来处理未来,所以如果有人遇到这个问题,请记住将 FutureBuilder 添加到您的 UI 主体并在构建器上返回您想要显示的小部件。

我正在制作一个待办事项列表教程,我正在尝试在我的 todoList 上添加对 JSON 进行编码的功能,并将其保存在 sharedPreferences 上,并在我启动应用程序时在屏幕上检索它

这是我的 TODO 课

class Todo  
Todo (this.title,this.isDone = false);
String title;
bool isDone;


//Decode method to convert a Json String into a Dynamic object
Todo.fromJson(Map <String, dynamic> json)
: title = json ["title"],
  isDone  = json ["isDone"];
Map <String,dynamic> toJson() =>

       "title" : title,
       "isDone" : isDone
;

这是我的屏幕

class _TodoListScreenState extends State<TodoListScreen> 
List<Todo> todos = [];
@override
void initState() 
super.initState();
 _getTodoFromSharedPreferences();





//updates the state of the checkbox and reflects it on the UI
_toggleTodo(Todo todo, bool isChecked) 
setState(() 
  todo.isDone = isChecked;
);


_addTodo() async 
final todo = await showDialog<Todo>(
  context: context,
builder:(BuildContext context)  // <- Here you draw the Dialog
  return NewTodoDialog();
,
);
if (todo != null) 
  setState(() 
    todos.add(todo);
    _saveTodo(todos);
    print(todos.length);

    );
   
   

   _saveTodo(List<Todo> todo) async
   final String newTodo = jsonEncode(todo);
   setSharedPreferences(newTodo);
   



    _getTodoFromSharedPreferences () async 
    final prefs = await SharedPreferences.getInstance();
    final savedTodo = prefs.getString("savedTodo");
    if (savedTodo == null) return null; else 
    Map MapofTodos = jsonDecode(savedTodo);
  for (var i = 0; i < MapofTodos.length; ++i) 
    var o = MapofTodos[i];
    setState(() 
      Todo todo = Todo.fromJson(o);
      todos.add(todo);
    );


  




 setSharedPreferences (String newTodo ) async
 final prefs = await SharedPreferences.getInstance();
 await prefs.setString("savedTodo", newTodo );
 print(newTodo);
 

 @override
  Widget build(BuildContext context) 
   return Scaffold(
            appBar: AppBar(backgroundColor:Colors.deepPurple[900] ,
               title: Text('Todo List')),
       body: TodoList(
         todos: todos,
         onTodoToggle: _toggleTodo,
       ),
       floatingActionButton: FloatingActionButton(
         backgroundColor: Colors.purpleAccent[700],
         child: Icon(Icons.add),
         onPressed: _addTodo,
       ),
   );
  


  

当我运行应用程序时出现此错误

E/flutter ( 7476): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] 
Unhandled Exception: type 'List<dynamic>' is not a subtype of type 
'Map<dynamic, dynamic>'
E/flutter ( 7476): #0      
_TodoListScreenState._getTodoFromSharedPreferences 
(package:flutter_todo/UI/todo_list_screen.dart:70:11)
E/flutter ( 7476): <asynchronous suspension>
E/flutter ( 7476): #1      _TodoListScreenState.initState 
(package:flutter_todo/UI/todo_list_screen.dart:29:6)
E/flutter ( 7476): #2      StatefulElement._firstBuild 
(package:flutter/src/widgets/framework.dart:3851:58)
E/flutter ( 7476): #3      ComponentElement.mount 
(package:flutter/src/widgets/framework.dart:3716:5)
E/flutter ( 7476): #4      Element.inflateWidget 
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #5      Element.updateChild 
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #6      SingleChildRenderObjectElement.mount 
(package:flutter/src/widgets/framework.dart:4881:14)
E/flutter ( 7476): #7      Element.inflateWidget 
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #8      Element.updateChild 
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #9      ComponentElement.performRebuild 
(package:flutter/src/widgets/framework.dart:3752:16)
E/flutter ( 7476): #10     Element.rebuild 
(package:flutter/src/widgets/framework.dart:3564:5)
E/flutter ( 7476): #11     ComponentElement._firstBuild 
(package:flutter/src/widgets/framework.dart:3721:5)
E/flutter ( 7476): #12     ComponentElement.mount 
(package:flutter/src/widgets/framework.dart:3716:5)
E/flutter ( 7476): #13     Element.inflateWidget 
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #14     Element.updateChild 
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #15     SingleChildRenderObjectElement.mount 
(package:flutter/src/widgets/framework.dart:4881:14)
E/flutter ( 7476): #16     Element.inflateWidget 
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #17     Element.updateChild 
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #18     SingleChildRenderObjectElement.mount 
(package:flutter/src/widgets/framework.dart:4881:14)
E/flutter ( 7476): #19     Element.inflateWidget 
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #20     Element.updateChild 
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #21     SingleChildRenderObjectElement.mount 
(package:flutter/src/widgets/framework.dart:4881:14)
E/flutter ( 7476): #22     Element.inflateWidget 
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #23     Element.updateChild 
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #24     SingleChildRenderObjectElement.mount 
(package:flutter/src/widgets/framework.dart:4881:14)
E/flutter ( 7476): #25     Element.inflateWidget 
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #26     Element.updateChild 
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #27     ComponentElement.performRebuild 
(package:flutter/src/widgets/framework.dart:3752:16)
E/flutter ( 7476): #28     Element.rebuild 
(package:flutter/src/widgets/framework.dart:3564:5)
E/flutter ( 7476): #29     ComponentElement._firstBuild 
(package:flutter/src/widgets/framework.dart:3721:5)
E/flutter ( 7476): #30     StatefulElement._firstBuild 
(package:flutter/src/widgets/framework.dart:3869:11)
E/flutter ( 7476): #31     ComponentElement.mount 
(package:flutter/src/widgets/framework.dart:3716:5)
E/flutter ( 7476): #32     Element.inflateWidget 
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #33     Element.updateChild 
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #34     ComponentElement.performRebuild 
(package:flutter/src/widgets/framework.dart:3752:16)
E/flutter ( 7476): #35     Element.rebuild 
(package:flutter/src/widgets/framework.dart:3564:5)
E/flutter ( 7476): #36     ComponentElement._firstBuild 
(package:flutter/src/widgets/framework.dart:3721:5)
E/flutter ( 7476): #37     ComponentElement.mount 
(package:flutter/src/widgets/framework.dart:3716:5)
E/flutter ( 7476): #38     Element.inflateWidget 
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #39     Element.updateChild 
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #40     ComponentElement.performRebuild 
(package:flutter/src/widgets/framework.dart:3752:16)
E/flutter ( 7476): #41     Element.rebuild 
(package:flutter/src/widgets/framework.dart:3564:5)
E/flutter ( 7476): #42     ComponentElement._firstBuild 
(package:flutter/src/widgets/framework.dart:3721:5)
E/flutter ( 7476): #43     StatefulElement._firstBuild 
(package:flutter/src/widgets/framework.dart:3869:11)
E/flutter ( 7476): #44     ComponentElement.mount 
(package:flutter/src/widgets/framework.dart:3716:5)
E/flutter ( 7476): #45     Ele

我尝试将列表更改为地图,但没有成功

除了将小部件返回到屏幕之外,我在所有方面都取得了成功。 请帮帮我:c

【问题讨论】:

试试这个var todo = Todo.fromJson(o); 【参考方案1】:

我之前遇到过这个问题,因为我想在共享首选项中保存一个数组对象。你可以试试这个。

//Save you array object as an array of Strings in Shared Preferences
 void _saveTodo(List<Todo> todo) async
  SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
  sharedPreferences.setStringList("savedTodo", _mapTodoData(todo));
 

将 JSON 转换为字符串数组

 List<String> _mapTodoData(List<dynamic> todos) async
  try 
      var res = todos.map((v) => json.encode(v)).toList();
      return res;
     catch (err) 
     // Just in case
      return [];
    
 

如果您想获取和转换 Todo 对象列表中的数据

void loadData() async 

 SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
 final todoArray = _decodeTodoData(sharedPreferences.getStringList("savedTodo"))
 //This is your array :) -> todoArray    

List<Todo> _decodeTodoData(List<String> todos) 
    try 
      //Transforming List<String> to Json
      var result = todos.map((v) => json.decode(v)).toList();
      //Transforming the Json into Array<Todo>
      var todObjects = result.map((v) => Todo.fromJson(v)).toList();
      return todObjects;
     catch (error) 
      return [];
    
  

这对我有用,我真的很努力解决这个问题。

我希望这对你也有用。

【讨论】:

嗨!感谢您快速详细的回复,现在我正在处理一个不同的问题,我不能使用 de saveTodo 方法它告诉我` [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] 未处理的异常:类型' Future' 不是 'List' 类型的子类型 _TodoListScreenState._saveTodo (package:flutter_todo/UI/todo_list_screen.dart:60:50) 并且代码线是这个 _mapTodoData(todo)); `【参考方案2】:

在这里,您尝试迭代 Map,这是不可能的,因为只有可能的 Iterables 对象是 Set、List 和 Queue。

// Map MapofTodos = jsonDecode(savedTodo); 
//Try to debug it first first and see what type it's returning
print(jsonDecode(savedTodo).runtimeType);

【讨论】:

【参考方案3】:

我在 dart 应用程序开发过程中遇到了同样的问题。 json 解码技术的问题或者可能是 json 转换。 我已经完成了将方法创建为传递参数的工作

getCardData(data[0]["cardContent"][0]["cardData"] as List),
  List<String> getCardData(data) 
    List<String> _cardInfo = [];
    for (int i = 0; i < data.length; i++) 
      _cardInfo.add(data[i] as String);
    
    return _cardInfo;
  

【讨论】:

以上是关于未处理的异常:类型 'List<dynamic>' 不是类型 'Map<String, dynamic>' 的子类型的主要内容,如果未能解决你的问题,请参考以下文章

未处理的异常:类型“List<dynamic>”不是“List<CustomerTransactionDetail>”类型的子类型

未处理的异常:类型 'List<dynamic>' 不是类型 'Map<String, dynamic>' 的子类型

未处理的异常:类型'List<dynamic>'不是'String'类型的子类型无法获取json数据[重复]

未处理的异常:类型 'List<dynamic>' 不是颤振中类型 'Map<dynamic, dynamic>' 的子类型

未处理的异常:类型“List<dynamic>”不是“List<Map<String, double>>”类型的子类型

未处理的异常:类型“int”不是类型转换中“List<int>”类型的子类型