简体   繁体   中英

Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>' in type cast

I try to render result requested from the server and its format is json data.

This is API return as json.

{
    id: 1,
    name: Nhel Theavuth,
    email: info@theavuth.me,
    username: theavuth,
    avatar: null,
    phone_number: null,
    token: 
}

User Model:

import 'package:flutter/foundation.dart';

class User with ChangeNotifier {
  int id;
  String fullName;
  String phoneNumber;
  String email;
  String username;
  String avatar;
  String token;

  User({
    this.id,
    this.fullName,
    this.phoneNumber,
    this.email,
    this.username,
    this.avatar,
    this.token
  });

  factory User.fromJson(dynamic json) {
    return User(
      id         : json['id'],
      fullName   : json['name'],
      phoneNumber: json['phone_number'],
      email      : json['email'],
      username   : json['username'],
      avatar     : json['avatar'],
      token      : json['token']
    );
  }

  Map<String, dynamic> toJson() => {
    'id'          : id,
    'name'        : fullName,
    'phone_number': phoneNumber,
    'email'       : email,
    'username'    : username,
    'avatar'      : avatar,
    'token'       : token
  };

}

This code to call dataJson from the server.

void getProfileData() async {
    SharedPreferences prefs           = await SharedPreferences.getInstance();
    String _token                     = prefs.getString('token');
    Map<String, dynamic> responseData = await _userProvider.userProfile({'token':  _token});
    print(responseData['data']);
    List<User> profileData            = (responseData['data'].toList()).map((parsedJson) => User.fromJson(parsedJson)).toList();

    setState(() {
      this.userProfile = profileData;
    });
  }

This error message after render the json above to user model.

[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>' in type cast

Anyone could help on this? Thanks in advance

I need to more information about what is happening, assingin code. But it seems like you need to call .toList() in order to get a List from your JSON result, because Dart manage json as Map.

You can copy paste run full code below
Assume your json string is

String jsonString = '''
    {
    "id": 1,
    "name": "Nhel Theavuth",
    "email": "info@theavuth.me",
    "username": "theavuth",
    "avatar": null,
    "phone_number": null,
    "token": ""
}
    ''';

Step 1: Modify your User.fromJson , you can see User definition in full code

factory User.fromJson(Map<String, dynamic> json) => User(
    id: json["id"],
    name: json["name"],
    email: json["email"],
    username: json["username"],
    avatar: json["avatar"],
    phoneNumber: json["phone_number"],
    token: json["token"],
  );

Step 2: parse json string with function userFromJson

User userFromJson(String str) => User.fromJson(json.decode(str));
...
User user = userFromJson(jsonString);
print(user.name);

output

I/flutter (12738): Nhel Theavuth

full code

import 'package:flutter/material.dart';
import 'dart:convert';

User userFromJson(String str) => User.fromJson(json.decode(str));

String userToJson(User data) => json.encode(data.toJson());

class User {
  int id;
  String name;
  String email;
  String username;
  dynamic avatar;
  dynamic phoneNumber;
  String token;

  User({
    this.id,
    this.name,
    this.email,
    this.username,
    this.avatar,
    this.phoneNumber,
    this.token,
  });

  factory User.fromJson(Map<String, dynamic> json) => User(
    id: json["id"],
    name: json["name"],
    email: json["email"],
    username: json["username"],
    avatar: json["avatar"],
    phoneNumber: json["phone_number"],
    token: json["token"],
  );

  Map<String, dynamic> toJson() => {
    "id": id,
    "name": name,
    "email": email,
    "username": username,
    "avatar": avatar,
    "phone_number": phoneNumber,
    "token": token,
  };
}


void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(       
        primarySwatch: Colors.blue,       
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    String jsonString = '''
    {
    "id": 1,
    "name": "Nhel Theavuth",
    "email": "info@theavuth.me",
    "username": "theavuth",
    "avatar": null,
    "phone_number": null,
    "token": ""
}
    ''';

    User user = userFromJson(jsonString);

    print(user.name);

    setState(() {     
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {    
    return Scaffold(
      appBar: AppBar(       
        title: Text(widget.title),
      ),
      body: Center(        
        child: Column(          
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM