我需要一個 DropdownButton,其中的專案取決于另一個 DropdownButton。聽起來有點混亂,但事實并非如此。這是我的代碼,在重要部分帶有注釋,以便理解我的意圖。
家長
class Parent extends StatefulWidget {
const Parent({ Key? key }) : super(key: key);
@override
State<Parent> createState() => _ParentState();
}
class _ParentState extends State<Parent> {
@override
Widget build(BuildContext context) {
return SafeArea(
child: SizedBox(
width: 500,
height: 500,
child: Column(
children: const [
// Main
DropDownWidget(collection: "MainCollection",),
// Depending
DropDownWidget(collection: ""), // Collection should equals value from Main DropDownWidget
],
),
),
);
}
}
孩子
class DropDownWidget extends StatefulWidget {
final String collection;
const DropDownWidget({Key? key, required this.collection}) : super(key: key);
@override
State<DropDownWidget> createState() => _DropDownWidgetState();
}
class _DropDownWidgetState extends State<DropDownWidget> {
var selectedItem;
@override
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection(widget.collection)
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData || snapshot.hasError) {
return const CircularProgressIndicator();
} else {
var length = snapshot.data?.docs.length;
List<DropdownMenuItem<String>> items = [];
for (int i = 0; i < length!; i ) {
DocumentSnapshot snap = snapshot.data!.docs[i];
items.add(DropdownMenuItem(
child: Text(snap.id),
value: snap.id,
));
}
return DropdownButtonFormField<String>(
onChanged: (value) {
setState(() {
selectedItem = value;
// ********************
// PASS value TO PARENT
// ********************
});
},
value: selectedItem,
items: items);
}
});
}
}
當 Main DropdownButton 更改其值時,它應該將其傳遞給我的父級,以更改我依賴的 DropdownButton 的焦點集合。我已經通過將所有代碼放在一個類中解決了這個問題,但這不是我想要的方式。所以也許你可以幫助我:)謝謝
uj5u.com熱心網友回復:
ValueChanged<String> onSelectItem在你的孩子身上制造一個論據。當值改變時呼叫該方法。
然后在您的父母中,您提供一個需要在您的孩子中的值發生變化時呼叫的函式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/442668.html
