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

Flutter中如何将menu_list.dart下拉框选中值传递到add_screen.dart并上传至FireStore

实现方案

通过回调函数实现子组件向父组件传值即可,不需要引入额外的状态管理库,修改两处代码即可:

1. 修改 menu_list.dart

给MenuList组件新增回调参数,用户选中下拉项时将值回传给父组件:

import 'package:flutter/material.dart';

class MenuList extends StatefulWidget {
  // 新增回调参数,用于回传选中值
  final ValueChanged<String?> onSelected;
  const MenuList({Key? key, required this.onSelected}) : super(key: key);
  @override
  _MenuListState createState() => _MenuListState();
}

class _MenuListState extends State<MenuList> {
  final items = ['Maths', 'Urdu', 'English', 'Simple'];

  String? value;

  @override
  Widget build(BuildContext context) {
    return DropdownButton<String>(
      value: value,
      isExpanded: true,
      items: items.map(buildMenuItem).toList(),
      onChanged: (value) => setState(
        () {
          this.value = value;
          // 选中后触发回调传值
          widget.onSelected(value);
        },
      ),
    );
  }
}

DropdownMenuItem<String> buildMenuItem(String item) => DropdownMenuItem(
      value: item,
      child: Text(
        item,
        style: TextStyle(
          fontWeight: FontWeight.bold,
          fontSize: 30,
        ),
      ),
    );

2. 修改 add_screen.dart

首先将原来的StatelessWidget改为StatefulWidget(符合Flutter可变状态的存储规范),接收子组件回传的下拉值,提交时一并上传到Firestore:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:database/widgets/menu_list.dart';
import 'package:flutter/material.dart';

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

  @override
  State<AddScreen> createState() => _AddScreenState();
}

class _AddScreenState extends State<AddScreen> {
  String? personname, personphone, selectedSubject;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Add Data"),
      ),
      body: Column(
        children: [
          Container(
            child: MenuList(
              // 接收子组件回传的选中值
              onSelected: (value) {
                selectedSubject = value;
              },
            ),
          ),
          const SizedBox(height: 15),
          Container(
            child: TextFormField(
              onChanged: (String name) {
                getStudentName(name);
              },
              decoration: const InputDecoration(
                labelText: "Name",
                focusedBorder: OutlineInputBorder(),
              ),
            ),
          ),
          const SizedBox(height: 15),
          Container(
            child: TextFormField(
              onChanged: (String phone) {
                getStudentPhone(phone);
              },
              decoration: const InputDecoration(
                labelText: "PhoneNumber",
                focusedBorder: OutlineInputBorder(),
              ),
            ),
          ),
          const SizedBox(height: 15),
          Container(
            child: ElevatedButton(
              child: const Text("Add"),
              onPressed: createData,
            ),
          ),
        ],
      ),
    );
  }

  createData() {
    FirebaseFirestore.instance
        .collection("Students")
        .doc("subcollection")
        .collection("collectionPath")
        .doc()
        .set(
      {
        "PersonName": personname,
        "PersonPhone": personphone,
        // 新增下拉选中的字段
        "SelectedSubject": selectedSubject,
      },
    );
  }

  getStudentName(name) {
    personname = name;
  }

  getStudentPhone(phone) {
    personphone = phone;
  }
}

注:代码中已将已经废弃的RaisedButton替换为Flutter官方推荐的ElevatedButton,如需保留原有组件可自行调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 14:09:03