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

Flutter/Dart新手求助:如何获取API的JSON Schema并对接指定API?

在Flutter中对接Realty Mole Property API的步骤

1. 获取API的实际JSON响应(替代缺失的Schema)

官方文档没提供JSON Schema的话,直接调用API拿到真实返回数据是最直接的方式:

  • 打开RapidAPI上该API的页面,找到你需要调用的具体接口(比如房产列表、详情接口)
  • 使用页面自带的「Try it out」功能,填写接口要求的参数(如城市、州),发送请求后就能看到完整的JSON返回结果
  • 复制这段JSON,用来生成对应的Dart数据模型

2. 生成Dart数据模型类

可以通过工具或手动编写来创建和JSON对应的模型类,这里推荐使用json_serializable来自动生成序列化代码:

第一步:添加依赖

在项目的pubspec.yaml中添加以下依赖:

dependencies:
  flutter:
    sdk: flutter
  http: ^1.1.0
  json_annotation: ^4.8.1

dev_dependencies:
  build_runner: ^2.4.4
  json_serializable: ^6.7.0

执行flutter pub get安装依赖。

第二步:编写模型类

假设你复制的JSON结构如下:

{
  "id": "12345",
  "address": "123 Main St",
  "price": 320000,
  "bedrooms": 3
}

创建对应的Dart类(比如property.dart):

import 'package:json_annotation/json_annotation.dart';

part 'property.g.dart';

@JsonSerializable()
class Property {
  final String id;
  final String address;
  final int price;
  final int bedrooms;

  Property({
    required this.id,
    required this.address,
    required this.price,
    required this.bedrooms,
  });

  // 从JSON解析为对象
  factory Property.fromJson(Map<String, dynamic> json) => _$PropertyFromJson(json);
  // 将对象转为JSON
  Map<String, dynamic> toJson() => _$PropertyToJson(this);
}

第三步:生成序列化代码

在终端执行以下命令:

flutter pub run build_runner build

工具会自动生成property.g.dart文件,包含序列化的实现代码。

3. 在Flutter中调用API获取数据

核心代码示例

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

class PropertyListScreen extends StatefulWidget {
  const PropertyListScreen({super.key});

  @override
  State<PropertyListScreen> createState() => _PropertyListScreenState();
}

class _PropertyListScreenState extends State<PropertyListScreen> {
  List<Property>? _properties;
  bool _isLoading = true;
  String? _errorMsg;

  Future<void> _fetchProperties() async {
    final apiUrl = Uri.parse('https://realtymole-property-api.p.rapidapi.com/properties/list?city=Austin&state=TX');
    final headers = {
      'X-RapidAPI-Key': '你的RapidAPI密钥', // 替换为你自己的密钥
      'X-RapidAPI-Host': 'realtymole-property-api.p.rapidapi.com'
    };

    try {
      final response = await http.get(apiUrl, headers: headers);
      if (response.statusCode == 200) {
        // 解析JSON数组为模型列表
        final List<dynamic> jsonData = response.body as List;
        setState(() {
          _properties = jsonData.map((item) => Property.fromJson(item)).toList();
        });
      } else {
        setState(() {
          _errorMsg = '请求失败:${response.statusCode}';
        });
      }
    } catch (e) {
      setState(() {
        _errorMsg = '请求出错:$e';
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('房产数据')),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _errorMsg != null
              ? Center(child: Text(_errorMsg!))
              : _properties == null
                  ? const Center(child: Text('无数据'))
                  : ListView.builder(
                      itemCount: _properties!.length,
                      itemBuilder: (context, index) {
                        final property = _properties![index];
                        return ListTile(
                          title: Text(property.address),
                          subtitle: Text('${property.bedrooms}室 | \$${property.price}'),
                        );
                      },
                    ),
    );
  }
}

关键注意事项

  • 确保你已在RapidAPI上订阅该API,否则请求会被拒绝
  • 替换代码中的「你的RapidAPI密钥」为你自己的密钥(在RapidAPI的「My Apps」页面可查看)
  • 根据实际返回的JSON结构调整模型类的字段,如果有嵌套对象,需要创建对应的嵌套模型类
  • 可以额外添加网络状态判断、超时处理等逻辑,提升用户体验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 00:53:14