【问题标题】:TypeError (type 'User' is not a subtype of type 'FutureOr<Either<Error, User>>'), even with same type return valueTypeError(类型 'User' 不是类型 'FutureOr<Either<Error, User>>' 的子类型),即使返回值相同
【发布时间】:2020-05-12 22:33:17
【问题描述】:

如何正确地将返回值分配给Future&lt;Either&lt;Error, User&gt;&gt;&gt;?因为我总是得到: _TypeError (type 'User' is not a subtype of type 'FutureOr&lt;Either&lt;Error, User&gt;&gt;') as required by the closure's context' 我什至给出了一个相同类型的返回值。

import 'package:dartz/dartz.dart';

class APIPenggunaHelper {
  final api=APIPengguna();
  Future<Either<Error,User>> ambildatauser() async{
    final hasilapi=await api.ambilSemuaData();
    return hasilapi.fold((l){
      // handling error
      if(hasilapi.length()<1) return Left(MasalahDataKosong());
      return Left(Masalah400());
    }, (r){
      // handling result
      print(r.toString());
      final user_= User.fromJson(jsonDecode(r));
      return Right(user);
    });
  }
}

上面的代码应该返回 user 这是一个User class 应该是,但它显示subtype error 我上面提到的。

这是print(r.toString())的输出

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  },
  .
  .
  .
  ]

编辑:

API.dart

class APIPengguna {
  final String linkpengguna='/users';
  Future<Either<Exception, dynamic>> ambilSemuaData() async{
    try {
      final mapbodi={
        "id":1,
        "username":"Bret"
      };
      // final uriapi=Uri.https('https://jsonplaceholder.typicode.com',linkpengguna);
      final uriapi='https://jsonplaceholder.typicode.com'+linkpengguna;
      Response respon=await get(uriapi);
      var status=respon.statusCode;
      var data=respon.body;
      // print('data: $data');
      if (status<200 || status>400) {
        throw new Exception('gagal ambil data');
      } else {
        return Right(data);     // data is a dynamic
      }
    } catch (e) {
      return (Left(Exception('gagal ambil data, eror: $e')));
    }
  }
}


list_user.dart

import 'package:appsa/aplikasi/perpustakaan.dart';

class DaftarUser{
  final List<User> pengguna;

  DaftarUser({this.pengguna});

  factory DaftarUser.fromJson(List<dynamic> jsonuser){
    List pengguna_=new List();
    pengguna_=jsonuser.map((p)=>User.fromJson(p)).toList();

    return new DaftarUser(
      pengguna:pengguna_
    );
  }
}


model_User.dart

import 'dart:convert';

class User {
  final int id;
  final String name;
  final String username;
  final String email;
  final Address address;
  final String phone;
  final String website;
  final Company company;
  User({
    this.id,
    this.name,
    this.username,
    this.email,
    this.address,
    this.phone,
    this.website,
    this.company,
  });

  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'name': name,
      'username': username,
      'email': email,
      'address': address?.toMap(),
      'phone': phone,
      'website': website,
      'company': company?.toMap(),
    };
  }

  static User fromMap(Map<String, dynamic> map) {
    if (map == null) return null;

    return User(
      id: map['id']?.toInt(),
      name: map['name'],
      username: map['username'],
      email: map['email'],
      address: Address.fromMap(map['address']),
      phone: map['phone'],
      website: map['website'],
      company: Company.fromMap(map['company']),
    );
  }

  String toJson() => jsonEncode(toMap());

  static User fromJson(String source) => fromMap(jsonDecode(source));

  @override
  String toString() {
    return 'User(id: $id, name: $name, username: $username, email: $email, address: $address, phone: $phone, website: $website, company: $company)';
  }

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您将 ambildatauser 函数的返回类型定义为

    Future<Either<Error,User>> ambildatauser() async{...}
    

    但你的函数实际上返回的是用户类型的值

    您必须将其更改为 return Right(user);

    【讨论】:

    • 我添加了User u=User.fromJson(jsonDecode(r)),但现在它显示了不同类型的相同错误,即_TypeError (type 'List&lt;dynamic&gt;' is not a subtype of type 'String')
    • 看起来您正在某个地方将列表映射为字符串。能贴出模型和用户类代码吗?
    • 如果你检查你的r.toString() 它是一个 JSON 对象列表,而你的用户模型需要一个 JSON 对象。也许这就是它抛出类型错误的原因
    • 我做了一个列表解析器,对我的代码稍作修改,它仍然显示not a subtype error
    • 是的,r.toString() 在 JSON 中返回一个 List,但它的类型是 dynamic
    猜你喜欢
    • 2020-08-13
    • 2022-01-03
    • 2021-04-13
    • 2020-09-01
    • 1970-01-01
    • 2021-10-02
    • 2020-11-26
    • 1970-01-01
    • 2022-11-14
    相关资源
    最近更新 更多