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

Flutter中通过POST请求获取API数据后如何在页面展示

如何将API返回的汽车数据展示在Flutter的Text组件中

我已经成功获取到API的响应数据,但目前只能在终端打印,不知道怎么把这些数据转换成可以在屏幕上显示的文本,希望能把API返回的汽车信息展示在Text组件里。

以下是我的相关代码:

class carList extends StatefulWidget {
  const carList({Key? key}) : super(key: key);

  @override
  State<carList> createState() => _carListState();
}

class _carListState extends State<carList> {

  var userController = TextEditingController();
  var apiController = TextEditingController();
  final pref = Pref();

  @override
  void initState() {
    MySharedPreferences().getUserId().then((value) {
      setState(() {
        userController.text = value.toString();
      });
    });
    MySharedPreferences().getUserToken().then((value) {
      setState(() {
        apiController.text = value.toString();
      });
    });
    //TODO: IMPLEMENT INITSTATE
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: ListView(
            children: <Widget>[
              Container(
                padding: const EdgeInsets.all(10),
                child: TextField(
                  controller: userController,
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    suffixIcon: Icon(Icons.email),
                    labelText: 'User ID',
                  ),
                ),
              ),
              Container(
                padding: const EdgeInsets.all(10),
                child: TextField(
                  controller: apiController,
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    suffixIcon: Icon(Icons.email),
                    labelText: 'Token',
                  ),
                ),
              ),
              Container(
                margin: EdgeInsets.all(25),
                child: TextButton(
                  child: Text('Show Car List',
                    style: TextStyle(fontSize: 20.0,
                        color: Colors.blueAccent,
                        backgroundColor: Colors.white),
                  ),
                  onPressed: () {
                    list();
                  },
                ),
              )
            ]
        )
    );
  }

void list() async {
        {
          var response = await http.post(
              Uri.parse("http://servisjer.me-tech.com.my/api/Car/GetUserCar"),
              body: ({
                'user_id': userController.text,
                'token': apiController.text,
                'device': "Android",
              }));
          if (response.statusCode == 200) {
            final body = jsonDecode(response.body);
            print(apiController.text);
            print(body.toString());
            ScaffoldMessenger.of(context)
                .showSnackBar(SnackBar(content: Text("Successfully Login")));
          }
        }
      }
}

API返回示例:

{
    "Status": "OK",
    "Message": "Senarai maklumat kereta.",
    "Details": [
      {
        "car_id": 184,
        "user_id": 141,
        "manufacturer_id": 21,
        "name": "Akma",
        "registration_no": "ws 3345",
        "model_name": "Bezza",
        "production_year": 2022,
        "notes": null,
        "date_purchased": "2022-08-10",
        "image": " http://servisjer.me-tech.com.my/admin/storage/app/media/userplugin/7PyVIp8iwb.png"
      }
    ]
  }

解决步骤

1. 创建数据模型类

先为API返回的汽车数据创建模型类,方便解析和管理数据:

class Car {
  final int carId;
  final int userId;
  final int manufacturerId;
  final String name;
  final String registrationNo;
  final String modelName;
  final int productionYear;
  final String? notes;
  final String datePurchased;
  final String image;

  Car({
    required this.carId,
    required this.userId,
    required this.manufacturerId,
    required this.name,
    required this.registrationNo,
    required this.modelName,
    required this.productionYear,
    this.notes,
    required this.datePurchased,
    required this.image,
  });

  // 从JSON解析为Car对象
  factory Car.fromJson(Map<String, dynamic> json) {
    return Car(
      carId: json['car_id'],
      userId: json['user_id'],
      manufacturerId: json['manufacturer_id'],
      name: json['name'],
      registrationNo: json['registration_no'],
      modelName: json['model_name'],
      productionYear: json['production_year'],
      notes: json['notes'],
      datePurchased: json['date_purchased'],
      image: json['image'],
    );
  }
}

2. 在状态类中添加数据存储变量

在_carListState中添加变量保存汽车列表:

class _carListState extends State<carList> {
  var userController = TextEditingController();
  var apiController = TextEditingController();
  final pref = Pref();
  // 添加汽车列表存储变量
  List<Car> carList = [];

  // 原有initState代码不变
}

3. 修改list方法解析并更新数据

更新list方法,将JSON数据解析为Car对象列表,再通过setState更新UI:

void list() async {
  var response = await http.post(
    Uri.parse("http://servisjer.me-tech.com.my/api/Car/GetUserCar"),
    body: ({
      'user_id': userController.text,
      'token': apiController.text,
      'device': "Android",
    }),
  );
  if (response.statusCode == 200) {
    final body = jsonDecode(response.body);
    // 解析Details数组为Car列表并更新状态
    setState(() {
      carList = (body['Details'] as List)
          .map((carJson) => Car.fromJson(carJson))
          .toList();
    });
    ScaffoldMessenger.of(context)
        .showSnackBar(const SnackBar(content: Text("已获取汽车列表")));
  } else {
    ScaffoldMessenger.of(context)
        .showSnackBar(const SnackBar(content: Text("获取数据失败")));
  }
}

4. 在UI中添加数据展示区域

修改build方法的ListView,在按钮下方添加汽车信息展示模块:

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: ListView(
      children: <Widget>[
        // 原有输入框和按钮代码不变
        Container(
          margin: const EdgeInsets.all(25),
          child: TextButton(
            child: const Text('显示汽车列表',
              style: TextStyle(fontSize: 20.0,
                  color: Colors.blueAccent,
                  backgroundColor: Colors.white),
            ),
            onPressed: () {
              list();
            },
          ),
        ),
        // 汽车信息展示区域
        if (carList.isNotEmpty)
          ...carList.map((car) {
            return Container(
              padding: const EdgeInsets.all(16),
              margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              decoration: BoxDecoration(
                border: Border.all(color: Colors.grey),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('车主姓名: ${car.name}', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
                  const SizedBox(height: 8),
                  Text('车牌号码: ${car.registrationNo}'),
                  Text('车型: ${car.modelName}'),
                  Text('生产年份: ${car.productionYear}'),
                  Text('购买日期: ${car.datePurchased}'),
                  // 可根据需求添加更多字段
                ],
              ),
            );
          }).toList(),
        if (carList.isEmpty)
          const Padding(
            padding: EdgeInsets.all(16),
            child: Text('点击按钮获取汽车列表'),
          ),
      ],
    ),
  );
}

完成以上修改后,点击"显示汽车列表"按钮,API返回的汽车信息就会以卡片形式展示在屏幕上。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 07:05:21