Flutter-未处理异常:类型'(动态)=>Null'不是'f'的类型'(字符串,动态)=>void'的子类型

laximzn5  于 2022-11-30  发布在  Flutter
关注(0)|答案(3)|浏览(151)

不确定为什么我会收到错误“Unhandled Exception:类型'(dynamic)=〉Null'不是'f'“的类型'(String,dynamic)=〉void'的子类型。所有操作似乎都已正确完成,但仍然出现错误
第一个

wztqucjr

wztqucjr1#

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可能是您的Shipping。

vqlkdk9b

vqlkdk9b2#

你可以复制粘贴运行下面的完整代码
可以将返回类型定义为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);
    }
  }

工作演示

全码

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()),
                                  ],
                                ),
                              ));
                        });
                  }
              }
            }));
  }
}
vlju58qv

vlju58qv3#

When I got this problem the issue was that the response I was receiving from the API didn't have the shape that my Dart model was expecting. Let me give you an example, and lets do it with your Shipping class.
Say your query is returning a Json for a Shipping like so:

{0:{
  'id':'1',
  'name':'name',
  'address':'address'
  },
 1:{...},
}

Now this is not what you are expecting when you defined the model here:

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);
     });

What you are expecting is a response like this:

[{
  'id':'1',
  'name':'name',
  'address':'address'
  },
 {...},
]

So following this example if I was to loop through the API response body, Dart would complain because I am accessing a 'key' instead of a 'Map'; and I think this is the issue you are facing. I tried to check against your API but the link was broken.

相关问题