Error: Unhandled Exception: type '_Internallinkedhashmap<String, Dynamic>' is not a subtype of type 'int' in Flutter

Asked

Viewed 579 times

0

Hey, how you doing? I am still learning flutter and am having a problem authenticating the user. Even if I receive the status 200, I cannot navigate to the authorized page. I wonder if someone could help me?

Thanks in advance

Login screen:

import 'package:celer_pesquisa_app/constantes.dart';
import 'package:celer_pesquisa_app/services/login_api.dart';
import 'package:celer_pesquisa_app/telas/recuperar_senha_tela.dart';
import 'package:celer_pesquisa_app/telas/iniciar_quiz_tela.dart';
import 'package:celer_pesquisa_app/utilidades/alert.dart';
import 'package:flutter/material.dart';

class LoginTela extends StatefulWidget {
  static const String id = 'login_tela';

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

class _LoginTelaState extends State<LoginTela> {
  String email;
  String password;
  final _ctrlLogin = TextEditingController();
  final _ctrlSenha = TextEditingController();
  final _formKey = GlobalKey<FormState>();

  _textFormField(
    String label,
    String hint, {
    bool senha = false,
    TextEditingController controller,
    FormFieldValidator<String> validator,
  }) {
    return TextFormField(
      style: kTextCorEscuro,
      controller: controller,
      validator: validator,
      obscureText: senha,
      decoration: InputDecoration(
          labelText: label,
          labelStyle: TextStyle(
            color: kButtonCor2,
          ),
          hintText: hint,
          contentPadding:
              EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.all(Radius.circular(32.0)),
          ),
          enabledBorder: OutlineInputBorder(
            borderSide: BorderSide(color: kButtonCor1, width: 1.0),
            borderRadius: BorderRadius.all(Radius.circular(32.0)),
          ),
          focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(color: kButtonCor1, width: 2.0),
            borderRadius: BorderRadius.all(Radius.circular(32.0)),
          )),
    );
  }

  String _validaLogin(String texto) {
    if (texto.isEmpty) {
      return 'Digite o email';
    }
    if (texto.length < 3) {
      return 'Email muito curto, insira novamente!';
    }
    return null;
  }

  String _validaSenha(String texto) {
    if (texto.isEmpty) {
      return "Digite o senha";
    }
    return null;
  }

  void _clickButton(BuildContext context) async {
    bool formOk = _formKey.currentState.validate();

    if (!formOk) {
      return;
    }

    String login = _ctrlLogin.text;
    String senha = _ctrlSenha.text;

    print('login: $login senha: $senha');

    var user = await LoginApi.login(login, senha);

    if (user != null) {
      //print('==> $user');
      _navegaQuizStart(context);
    } else {
      alert(context, "Login Inválido!");
    }
  }

  _navegaQuizStart(BuildContext context) {
    Navigator.pushNamed(context, IniciarQuiz.id);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: FlatButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: Icon(
            Icons.arrow_back_ios,
            size: 50.0,
            color: kButtonCor2,
          ),
        ),
      ),
      backgroundColor: Colors.white,
      body: Form(
        key: _formKey,
        child: ListView(children: [
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 24.0),
            child: SafeArea(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  SizedBox(
                    height: 48.0,
                  ),
                  _textFormField('Login', 'Digite o email',
                      controller: _ctrlLogin, validator: _validaLogin),
                  SizedBox(
                    height: 8.0,
                  ),
                  _textFormField('Senha', 'Digite a senha',
                      senha: true,
                      controller: _ctrlSenha,
                      validator: _validaSenha),
                  SizedBox(
                    height: 24.0,
                  ),
                  Padding(
                    padding: EdgeInsets.symmetric(vertical: 16.0),
                    child: Material(
                      color: kButtonCor1,
                      borderRadius: BorderRadius.all(Radius.circular(30.0)),
                      elevation: 5.0,
                      child: MaterialButton(
                        onPressed: () {
                          _clickButton(context);
                        },
                        minWidth: 200.0,
                        height: 42.0,
                        child: Text(
                          'Entrar',
                          style: kTextCorClaro,
                        ),
                      ),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.symmetric(vertical: 16.0),
                    child: Material(
                      color: kButtonCor2,
                      borderRadius: BorderRadius.circular(30.0),
                      elevation: 5.0,
                      child: MaterialButton(
                        onPressed: () {
                          Navigator.pushNamed(context, RecuperarSenhaTela.id);
                        },
                        minWidth: 200.0,
                        height: 42.0,
                        child: Text(
                          'Esqueci a Senha',
                          style: kTextCorClaro,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ]),
      ),
    );
  }
}

Login-api

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:celer_pesquisa_app/services/user_info.dart';

class LoginApi {
  static Future<UserInfo> login(String username, String password) async {
    final baseUrl = 'https://iopoc.celer.ind.br:8080/api/v1/';

    var url = '$baseUrl/auth/user/login/';

    //Content-Type
    var header = {
      "Content-Type": "application/json",
      "Authorization": "Token <TOKEN>"
    };
    //Body
    Map params = {"username": username, "password": password};

    var userInfo;

    
    var _body = json.encode(params);

    var response = await http.post(url, headers: header, body: _body);

    print('Response status: ${response.statusCode}');
    //print('Response body: ${response.body}');

    Map mapResponse = json.decode(response.body);
    if (response.statusCode == 200)

      userInfo = UserInfo.fromJson(mapResponse);
    } else {
      userInfo = null;
    }
    return userInfo;
  }
}

Model

class UserInfo {
  UserInfo({
    this.user,
    this.token,
  });

  User user;
  String token;

  factory UserInfo.fromRawJson(String str) =>
      UserInfo.fromJson(json.decode(str));

  String toRawJson() => json.encode(toJson());

  factory UserInfo.fromJson(Map<String, dynamic> json) => UserInfo(
        user: User.fromJson(json["user"]),
        token: json["token"],
      );

  Map<String, dynamic> toJson() => {
        "user": user.toJson(),
        "token": token,
      };

  String toString() {
    return 'User(token: $token, user: $user )';
  }
}

class User {
  User({
    this.id,
    this.fullName,
    this.email,
    this.profile,
    this.phones,
    this.company,
    this.tads,
    this.createDate,
    this.createUser,
    this.lastUpdateDate,
    this.lastUpdateUser,
    this.isActive,
  });

  int id;
  String fullName;
  String email;
  String profile;
  List<Phone> phones;
  Company company;
  List<dynamic> tads;
  DateTime createDate;
  AteUser createUser;
  DateTime lastUpdateDate;
  AteUser lastUpdateUser;
  bool isActive;

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

  String toRawJson() => json.encode(toJson());

  factory User.fromJson(Map<String, dynamic> json) => User(
        id: json["id"],
        fullName: json["fullName"],
        email: json["email"],
        profile: json["profile"],
        phones: List<Phone>.from(json["phones"].map((x) => Phone.fromJson(x))),
        company: Company.fromJson(json["company"]),
        tads: List<dynamic>.from(json["tads"].map((x) => x)),
        createDate: DateTime.parse(json["createDate"]),
        createUser: AteUser.fromJson(json["createUser"]),
        lastUpdateDate: DateTime.parse(json["lastUpdateDate"]),
        lastUpdateUser: AteUser.fromJson(json["lastUpdateUser"]),
        isActive: json["isActive"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "fullName": fullName,
        "email": email,
        "profile": profile,
        "phones": List<dynamic>.from(phones.map((x) => x.toJson())),
        "company": company.toJson(),
        "tads": List<dynamic>.from(tads.map((x) => x)),
        "createDate": createDate.toIso8601String(),
        "createUser": createUser.toJson(),
        "lastUpdateDate": lastUpdateDate.toIso8601String(),
        "lastUpdateUser": lastUpdateUser.toJson(),
        "isActive": isActive,
      };
}

class Company {
  Company({
    this.id,
    this.name,
    this.cnpj,
    this.email,
    this.responsibleName,
    this.responsibleEmail,
    this.responsiblePhone,
    this.street,
    this.number,
    this.complement,
    this.neighborhood,
    this.city,
    this.state,
    this.country,
    this.zipcode,
    this.phones,
    this.branch,
    this.createDate,
    this.createUser,
    this.lastUpdateDate,
    this.lastUpdateUser,
    this.isActive,
  });

  int id;
  String name;
  String cnpj;
  String email;
  String responsibleName;
  String responsibleEmail;
  String responsiblePhone;
  dynamic street;
  dynamic number;
  dynamic complement;
  dynamic neighborhood;
  dynamic city;
  dynamic state;
  dynamic country;
  dynamic zipcode;
  List<dynamic> phones;
  dynamic branch;
  DateTime createDate;
  AteUser createUser;
  DateTime lastUpdateDate;
  AteUser lastUpdateUser;
  bool isActive;

  factory Company.fromRawJson(String str) => Company.fromJson(json.decode(str));

  String toRawJson() => json.encode(toJson());

  factory Company.fromJson(Map<String, dynamic> json) => Company(
        id: json["id"],
        name: json["name"],
        cnpj: json["cnpj"],
        email: json["email"],
        responsibleName: json["responsibleName"],
        responsibleEmail: json["responsibleEmail"],
        responsiblePhone: json["responsiblePhone"],
        street: json["street"],
        number: json["number"],
        complement: json["complement"],
        neighborhood: json["neighborhood"],
        city: json["city"],
        state: json["state"],
        country: json["country"],
        zipcode: json["zipcode"],
        phones: List<dynamic>.from(json["phones"].map((x) => x)),
        branch: json["branch"],
        createDate: DateTime.parse(json["createDate"]),
        createUser: AteUser.fromJson(json["createUser"]),
        lastUpdateDate: DateTime.parse(json["lastUpdateDate"]),
        lastUpdateUser: AteUser.fromJson(json["lastUpdateUser"]),
        isActive: json["isActive"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "name": name,
        "cnpj": cnpj,
        "email": email,
        "responsibleName": responsibleName,
        "responsibleEmail": responsibleEmail,
        "responsiblePhone": responsiblePhone,
        "street": street,
        "number": number,
        "complement": complement,
        "neighborhood": neighborhood,
        "city": city,
        "state": state,
        "country": country,
        "zipcode": zipcode,
        "phones": List<dynamic>.from(phones.map((x) => x)),
        "branch": branch,
        "createDate": createDate.toIso8601String(),
        "createUser": createUser.toJson(),
        "lastUpdateDate": lastUpdateDate.toIso8601String(),
        "lastUpdateUser": lastUpdateUser.toJson(),
        "isActive": isActive,
      };
}

class AteUser {
  AteUser({
    this.id,
    this.createDate,
    this.lastUpdateDate,
    this.isActive,
    this.fullName,
    this.profile,
    this.createUser,
    this.lastUpdateUser,
    this.user,
    this.company,
    this.tads,
    this.email,
  });

  int id;
  DateTime createDate;
  DateTime lastUpdateDate;
  bool isActive;
  String fullName;
  String profile;
  int createUser;
  int lastUpdateUser;
  int user;
  int company;
  List<dynamic> tads;
  String email;

  factory AteUser.fromRawJson(String str) => AteUser.fromJson(json.decode(str));

  String toRawJson() => json.encode(toJson());

  factory AteUser.fromJson(Map<String, dynamic> json) => AteUser(
        id: json["id"],
        createDate: DateTime.parse(json["createDate"]),
        lastUpdateDate: DateTime.parse(json["lastUpdateDate"]),
        isActive: json["isActive"],
        fullName: json["fullName"],
        profile: json["profile"],
        createUser: json["createUser"],
        lastUpdateUser: json["lastUpdateUser"],
        user: json["user"],
        company: json["company"] == null ? null : json["company"],
        tads: List<dynamic>.from(json["tads"].map((x) => x)),
        email: json["email"] == null ? null : json["email"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "createDate": createDate.toIso8601String(),
        "lastUpdateDate": lastUpdateDate.toIso8601String(),
        "isActive": isActive,
        "fullName": fullName,
        "profile": profile,
        "createUser": createUser,
        "lastUpdateUser": lastUpdateUser,
        "user": user,
        "company": company == null ? null : company,
        "tads": List<dynamic>.from(tads.map((x) => x)),
        "email": email == null ? null : email,
      };
}

class Phone {
  Phone({
    this.phone,
    this.description,
  });

  String phone;
  String description;

  factory Phone.fromRawJson(String str) => Phone.fromJson(json.decode(str));

  String toRawJson() => json.encode(toJson());

  factory Phone.fromJson(Map<String, dynamic> json) => Phone(
        phone: json["phone"],
        description: json["description"],
      );

  Map<String, dynamic> toJson() => {
        "phone": phone,
        "description": description,
      };
}

Print of json: json estrutura Error print:erro

  • You could edit your question and ask how the json template is coming AteUser? By the looks of it, some of your fields are not coming as you expect.

  • Your problem is you’re trying to set a Map<String, dynamic> to the property Ateuser.cmpany who’s kind Int. You need to create a class Company and do the same in other places company = Company.fromJson().

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.