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

Flutter实现基于Rest API的分类名称下拉列表及数据存储方案

解决方案

1. 修复视图文件(category_view.dart)

你的视图目前未绑定GetX控制器,无法获取API返回的分类数据。以下是修改后的完整代码:

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shivaram/controller/category_controller.dart';
import 'package:shivaram/model/category.dart';
import 'animation/fadeanimation.dart';

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

  @override
  State<CategoryView> createState() => _CategoryViewState();
}

class _CategoryViewState extends State<CategoryView> {
  // 初始化GetX控制器
  final CategoryController categoryController = Get.put(CategoryController());
  // 存储选中的完整分类对象(而非仅名称),方便后续存储
  CategoryModel? selectedCategory;

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          FadeAnimation(
            1.2,
            Padding(
              padding: EdgeInsets.only(top: 5),
              child: Container(
                height: 50,
                decoration: BoxDecoration(
                    border: Border.all(),
                    borderRadius: BorderRadius.circular(20)),
                child: Obx(() {
                  // 监听加载状态,显示加载动画或下拉列表
                  if (categoryController.isLoading.value) {
                    return Center(child: CircularProgressIndicator());
                  } else {
                    return DropdownButton<CategoryModel>(
                      // 从控制器的分类列表生成选项
                      items: categoryController.categoryList.map((category) {
                        return DropdownMenuItem(
                          child: Text(
                            category.catName,
                            style: TextStyle(color: Colors.black),
                          ),
                          value: category,
                        );
                      }).toList(),
                      onChanged: (CategoryModel? selected) {
                        setState(() {
                          selectedCategory = selected;
                          // 调用存储逻辑,将选中的分类存入目标表
                          _saveSelectedCategory(selected);
                        });
                      },
                      value: selectedCategory,
                      hint: Text(
                        '选择分类',
                        style: TextStyle(color: Colors.black),
                      ),
                      isExpanded: true, // 让下拉按钮占满容器宽度
                      underline: SizedBox(), // 移除默认下划线
                    );
                  }
                }),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 选中分类后的存储方法示例
  void _saveSelectedCategory(CategoryModel? category) {
    if (category == null) return;
    // 这里可以调用API将分类数据发送到后端存储,或使用本地数据库(如sqflite)
    // 示例:调用存储API
    // saveCategoryToAnotherTable(category);
    print('选中的分类:${category.catName},ID:${category.id}');
  }
}

2. 关键修改说明

  • 引入并初始化GetX控制器,通过Obx监听分类列表和加载状态的变化
  • 将下拉选项类型改为CategoryModel,保留完整分类信息(ID、名称等),便于后续存储
  • 添加加载状态处理,数据未加载完成时显示加载动画
  • 新增_saveSelectedCategory方法,处理选中分类后的存储逻辑

3. 补充配置

确保main.dart使用GetMaterialApp作为根组件,否则GetX无法正常工作:

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shivaram/view/category_view.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: CategoryView(),
    );
  }
}

4. 存储逻辑实现建议

如果需要将选中的分类存储到后端的另一个表中,可以在categoryapi.dart新增存储方法:

// 在categoryapi.dart中新增存储方法
static Future<void> saveCategoryToAnotherTable(CategoryModel category) async {
  final response = await http.post(
    Uri.parse('http://127.0.0.1:8000/api/save-category'),
    headers: {'Content-Type': 'application/json'},
    body: json.encode(category.toJson()),
  );
  if (response.statusCode != 200) {
    throw Exception('存储分类失败');
  }
}

然后在_saveSelectedCategory中调用该方法即可。

内容的提问来源于stack exchange,提问作者Shiva Ram Bhatta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 08:15:29