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

Flutter访问Supabase外键字段为何无空值却报Null错误?

Flutter访问Supabase外键字段时出现Null类型错误

我在Flutter中访问Supabase数据库的外键字段,Supabase控制台里表的所有行都没有空值,但模拟器运行应用时,第53行title: Text(data['payee(name)'])抛出_TypeError (type 'Null' is not a subtype of type 'String')异常。

侧边栏变量检查显示:

  • data = Map (4个元素)
    • 0 = "id" -> 2
    • 1 = "date" -> "2019-05-01"
    • 2 = "amount" -> 1290
    • 3 = "payee_id" -> Map (1个元素)
      • key = "payee_id"
      • value = Map (1个元素)
        • 0 = "name" -> "Goosehead Insurance"
  • index = 0

我的视图代码如下:

class HomePage extends StatelessWidget {
  HomePage({super.key});
  final SupabaseClient supabase = Supabase.instance.client;

  Future<List> readData() async {
    final result = await supabase.from('transactions').select('''
    id,
    date,
    amount,
    payee_id (name)
    ''');
    return result;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Supabase Course'),
        actions: [
          IconButton(
            onPressed: () async {
              await supabase.auth.signOut();
            },
            icon: const Icon(Icons.logout),
          )
        ],
      ),
      body: FutureBuilder(
        future: readData(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.hasError) {
            return Center(
              child: Text(snapshot.error.toString()),
            );
          }

          if (snapshot.hasData) {
            if (snapshot.data.length == 0) {
              return const Center(
                child: Text("No data available.\n Create new data"),
              );
            }
            return ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (BuildContext context, int index) {
                var data = snapshot.data[index];
                return ListTile(
                  title: Text(data['payee(name)']), // <---error here!
                  trailing: IconButton(
                    onPressed: () {
                      Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) =>
                                  EditPage(data['id'].toString(), data['id'])));
                    },
                    icon: const Icon(Icons.chevron_right_outlined),
                  ),
                );
              },
            );
          }

          return const Center(
            child: CircularProgressIndicator(),
          );
        },
      ),
    );
  }
}

解决方案

问题出在嵌套字段的访问方式错误:Supabase返回的结构里,payee_id是一个嵌套Map,内部包含name字段,而非你写的payee(name)。

  1. 修正字段访问路径
    将data['payee(name)']改为data['payee_id']['name'],修改后的ListTile代码:
return ListTile(
  title: Text(data['payee_id']['name']),
  trailing: IconButton(
    onPressed: () {
      Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) =>
                  EditPage(data['id'].toString(), data['id'])));
    },
    icon: const Icon(Icons.chevron_right_outlined),
  ),
);
  1. 添加空值防护(可选)
    为避免潜在的空值异常,建议使用空值运算符做兜底:
title: Text(data['payee_id']?['name'] ?? 'Unknown Payee'),

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 09:41:01