Flutter-未处理的异常:类型'(dynamic)=> Null'不是'f'类型'(String,dynamic)=> void'的子类型

时间:2020-06-02 17:12:48

标签: flutter

不确定出现错误的原因“未处理的异常:类型'(dynamic)=> Null'不是'f'类型的'(String,dynamic)=> void'的子类型”。一切似乎都正确完成,但仍然出现错误

Json link: https://androidapp.factory2homes.com/api/get-shipping-address-by-user-id/3
class ShippingAddressPage extends StatefulWidget {
  @override
  _ShippingAddressPageState createState() => _ShippingAddressPageState();
}

class _ShippingAddressPageState extends State<ShippingAddressPage> {

  List<Shipping> _shippingAddressList = List<Shipping>();

 @override
 void initState() {
   super.initState();
   _getShippingAddressByUserId();
 }


 _getShippingAddressByUserId() async {
   SharedPreferences _prefs = await SharedPreferences.getInstance();
   int _userId = _prefs.getInt('userId');
   ShippingAddressService _shippingAddressService = ShippingAddressService();
   var result = await _shippingAddressService.getShippingAddressByUserId(_userId);
   var shipping = json.decode(result.body);
   shipping.forEach((shipping){
     var model = Shipping();
     model.id = shipping['id'];
     model.name = shipping['name'];
     model.address = shipping['address'];
     setState(() {
       _shippingAddressList.add(model);
     });
   });
 }
E/flutter (26002): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'f'
E/flutter (26002): #0      _ShippingAddressPageState._getShippingAddressByUserId (package:factory2homes/screens/shipping_address_page.dart:32:13)
E/flutter (26002): <asynchronous suspension>
E/flutter (26002): #1      _ShippingAddressPageState.initState (package:factory2homes/screens/shipping_address_page.dart:22:4)
class ShippingAddressService{
  Repository _repository;

  ShippingAddressService(){
    _repository = Repository();
  }

  getShippingAddressByUserId(int userId) async {
    return await _repository.httpGetById('get-shipping-address-by-user-id', userId);
  }

}

2 个答案:

答案 0 :(得分:0)

ShippingAddressService()是否具有默认构造函数以外的构造函数?如果是这样,请将其添加到您的代码示例。 **

您的代码:

  getShippingAddressByUserId(int userId) async {
    return await _repository.httpGetById('get-shipping-address-by-user-id', userId);
  }

我在一个以上的职业上遇到过类似的问题。我的解决方案是将代码更改为:

ShippingAddress getShippingAddressByUserId(int userId) async {

    ShippingAddress _shippingAddress = await _repository.httpGetById('get-shipping-address-by-user-id', userId);

    return _shippingAddress;
  }

一如既往,YMMV。

进一步查看您的代码,我的ShippingAddress可能是您的运输。

答案 1 :(得分:0)

您可以在下面复制粘贴运行完整代码
您可以将返回类型定义为getShippingAddressByUserId()_getShippingAddressByUserId()
您可以用完整代码

检查类Shipping的定义和FutureBuilder

代码段

Future<http.Response> getShippingAddressByUserId(int userId) async {
    //return await _repository.httpGetById('get-shipping-address-by-user-id', userId);
    return await http.get(
        "https://androidapp.factory2homes.com/api/get-shipping-address-by-user-id/3");
  }

Future<Shipping> _getShippingAddressByUserId() async {
    //SharedPreferences _prefs = await SharedPreferences.getInstance();
    int _userId = 3; //_prefs.getInt('userId');
    ShippingAddressService _shippingAddressService = ShippingAddressService();
    var result =
        await _shippingAddressService.getShippingAddressByUserId(_userId);
    if (result.statusCode == 200) {
      return shippingFromJson(result.body);
    }
  }  

工作演示

enter image description here

完整代码

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

Shipping shippingFromJson(String str) => Shipping.fromJson(json.decode(str));

String shippingToJson(Shipping data) => json.encode(data.toJson());

class Shipping {
  Shipping({
    this.data,
  });

  List<Datum> data;

  factory Shipping.fromJson(Map<String, dynamic> json) => Shipping(
        data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "data": List<dynamic>.from(data.map((x) => x.toJson())),
      };
}

class Datum {
  Datum({
    this.id,
    this.name,
    this.address,
    this.userId,
    this.createdAt,
    this.updatedAt,
  });

  int id;
  String name;
  String address;
  int userId;
  DateTime createdAt;
  DateTime updatedAt;

  factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        id: json["id"],
        name: json["name"],
        address: json["address"],
        userId: json["user_id"],
        createdAt: DateTime.parse(json["created_at"]),
        updatedAt: DateTime.parse(json["updated_at"]),
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "name": name,
        "address": address,
        "user_id": userId,
        "created_at": createdAt.toIso8601String(),
        "updated_at": updatedAt.toIso8601String(),
      };
}

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: ShippingAddressPage(title: 'Flutter Demo Home Page'),
    );
  }
}

class ShippingAddressService {
  //Repository _repository;

  ShippingAddressService() {
    //_repository = Repository();
  }

  Future<http.Response> getShippingAddressByUserId(int userId) async {
    //return await _repository.httpGetById('get-shipping-address-by-user-id', userId);
    return await http.get(
        "https://androidapp.factory2homes.com/api/get-shipping-address-by-user-id/3");
  }
}

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

  final String title;

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

class _ShippingAddressPageState extends State<ShippingAddressPage> {
  int _counter = 0;
  Future<Shipping> _future;

  Future<Shipping> _getShippingAddressByUserId() async {
    //SharedPreferences _prefs = await SharedPreferences.getInstance();
    int _userId = 3; //_prefs.getInt('userId');
    ShippingAddressService _shippingAddressService = ShippingAddressService();
    var result =
        await _shippingAddressService.getShippingAddressByUserId(_userId);
    if (result.statusCode == 200) {
      return shippingFromJson(result.body);
    }
  }

  @override
  void initState() {
    _future = _getShippingAddressByUserId();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: FutureBuilder(
            future: _future,
            builder: (context, AsyncSnapshot<Shipping> snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                  return Text('none');
                case ConnectionState.waiting:
                  return Center(child: CircularProgressIndicator());
                case ConnectionState.active:
                  return Text('');
                case ConnectionState.done:
                  if (snapshot.hasError) {
                    return Text(
                      '${snapshot.error}',
                      style: TextStyle(color: Colors.red),
                    );
                  } else {
                    return ListView.builder(
                        itemCount: snapshot.data.data.length,
                        itemBuilder: (context, index) {
                          return Card(
                              elevation: 6.0,
                              child: Padding(
                                padding: const EdgeInsets.only(
                                    top: 6.0,
                                    bottom: 6.0,
                                    left: 8.0,
                                    right: 8.0),
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text(snapshot.data.data[index].name),
                                    Spacer(),
                                    Text(snapshot.data.data[index].id
                                        .toString()),
                                  ],
                                ),
                              ));
                        });
                  }
              }
            }));
  }
}