You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter提交订单触发HttpException:对象引用未设置为实例

Fixing "Object reference not set to an instance of an object" in Flutter Order Submission

Let's break down the issue you're facing. That server error usually means it's trying to access a property on an object that doesn't exist—either it received null where it expected an object, or the JSON payload is malformed. Here's the most likely culprit and how to fix it:

1. Critical Issue: Double JSON Encoding

Looking at your addOrder method, you're making a common mistake: encoding the payload twice.

You first convert your data map to a JSON string:

var bodyParams = json.encode({/* your order data */});

Then you encode that string again when sending the request:

body: json.encode(bodyParams)

This results in the server receiving a stringified version of a JSON string (not the raw JSON object it expects). When it tries to parse this, it can't find the required properties, leading to the "object reference" error.

Fix: Remove the second json.encode and pass bodyParams directly:

final response = await retry(
    () => http
        .post(url, headers: {
          "content-type": "application/json",
          "Accept": "application/json",
          "Authorization": "Bearer " + accessToken
        }, body: bodyParams) // Use the already-encoded string here
        .timeout(Duration(seconds: 5)),
    retryIf: (e) => e is SocketException || e is TimeoutException);

2. Check for Null Values in Request Parameters

Even after fixing the encoding, there are a few edge cases where nulls might slip into your payload and cause server errors:

a. TableNumber Handling

If _tableNumber is null (e.g., for delivery orders, not in-branch dining), calling toString() on it will create issues. Update the payload to handle this scenario:

"TableNumber": orderRequest.inBranch 
    ? (orderRequest.tableNumber?.toString() ?? "") 
    : "", // Or use null, depending on what your API expects for non-in-branch orders

b. Optional Objects (DeliveryAddress & PromoCode)

Your current code sends an empty object {} when addressId or promoCodeId is 0. Some APIs expect null instead of an empty object for optional fields. Try modifying these lines:

"DeliveryAddress": orderRequest.addressId == 0 ? null : {"Id": orderRequest.addressId},
"PromoCode": orderRequest.promoCodeId == 0 ? null : {"Id": orderRequest.promoCodeId},

c. Ensure Cart Items Aren't Null

In your screen's _addOrder method, make sure _cartItemsList is never null—even if there are no items, initialize it as an empty list:

// In your screen class, where _cartItemsList is declared
List<OrderItem> _cartItemsList = [];

d. Guard Against Null Selected Address

If _selectedAddress could ever be null, add a null check when setting addressId:

request.addressId = _selectedAddress?.id ?? 0;

3. Verify API Contract

Double-check your API documentation to confirm:

  • Which fields are required vs. optional
  • How optional fields should be represented (null, empty object, or omitted entirely)
  • Exact data types (e.g., does TableNumber need to be a number, or is a string acceptable?)

After making these changes, test your order submission again. The double encoding was almost certainly the main cause of the server error, but fixing the null edge cases will prevent similar issues in the future.

内容的提问来源于stack exchange,提问作者Ahmad Mohy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 14:22:41