问题描述
模型:为类别制作此模型。
import 'package:cloud_firestore/cloud_firestore.dart';
class CatagoryModel {
String id;
String catagoryname;
Timestamp date;
bool status;
String user;
CatagoryModel(this.id,this.catagoryname,this.date,this.user,this.status);
CatagoryModel.fromDocumentSnapshot(DocumentSnapshot documentSnapshot) {
id = documentSnapshot.id;
catagoryname = documentSnapshot.data()['catagoryname'];
date = documentSnapshot.data()['date'];
user = documentSnapshot.data()['user'];
status = documentSnapshot.data()['status'];
}
}
Service:此代码处理模型和 Firestore 数据并将其传递给 Getx 控制器。
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:get/get.dart';
import 'package:talhatraders/app/data/catagorymodel.dart';
class Database {
final FirebaseFirestore _firebase = FirebaseFirestore.instance;
Future<void> catagoryAdd(String catagoryname,bool status) async {
try {
await _firebase.collection('catagorydb').add({
'date': Timestamp.now(),'status': status,'catagoryname': catagoryname,'user':'user1'
});
} catch (e) {
print(e);
}
}
Future<void> catagoryStatus(CatagoryModel catagorymodel)async{
try {
await _firebase.collection('catagorydb').doc(catagorymodel.id).update({'status':!catagorymodel.status});
} catch (e) {
print(e);
}
}
Future<void> catagoryDelete(CatagoryModel catagorymodel)async{
try {
await _firebase.collection('catagorydb').doc(catagorymodel.id).delete();
} catch (e) {
}
}
Stream<List<CatagoryModel>> catagoryStream() {
return _firebase
.collection('catagorydb')
.snapshots()
.map((QuerySnapshot querysnapshot) {
List<CatagoryModel> todoData= List();
querysnapshot.docs.forEach((element) {
todoData.add(CatagoryModel.fromDocumentSnapshot(element));
});
return todoData;
});
}
}
Getx 控制器:这里我使用了 obs 字符串,该字符串在从 dropbox 中选择新值时发生变化
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:talhatraders/app/data/catagorymodel.dart';
import 'package:talhatraders/app/modules/catagory/controllers/catagoryservice.dart';
class ProductentryController extends GetxController {
Rx<List<CatagoryModel>> catagoryList = Rx<List<CatagoryModel>>();
List<CatagoryModel> get catagories => catagoryList.value;
var selectedItem = "Select Catagory..".obs;
void changeSelect(String select) {
selectedItem.value = select;
}
@override
void onInit() {
catagoryList.bindStream(Database().catagoryStream());
}
}
GetxViewPaege:在 ViewPage UI 中工作正常,但从下拉列表中选择新值时值没有改变
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter/services.dart';
import 'package:talhatraders/app/data/catagorymodel.dart';
import 'package:talhatraders/app/modules/catagory/controllers/catagory_controller.dart';
import 'package:talhatraders/app/modules/productentry/controllers/productentry_controller.dart';
class ProductentryView extends GetView<ProductentryController> {
ProductentryController productController = Get.put(ProductentryController());
final FirebaseFirestore _firebase = FirebaseFirestore.instance;
//Color currentColor =Colors.limeAccent;
String catagory;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('New Item'),actions: [],),body: Column(children: [
GetX<ProductentryController>(
init: Get.put<ProductentryController>(ProductentryController()),builder: (ProductentryController productentryController) {
return Expanded(
child: Container(
child: Padding(
padding: const EdgeInsets.only(
bottom: 12,top:40,left: 10.0,right: 15.0),child: InputDecorator(
decoration: InputDecoration(
fillColor: Colors.transparent,hintStyle: Theme.of(context).textTheme.bodyText2,border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),borderSide: BorderSide(
width: 10,style: BorderStyle.none,filled: true,contentPadding: EdgeInsets.all(16),child: DropdownButtonHideUnderline(
child: DropdownButton(
isExpanded: true,isDense:
true,// Reduces the dropdowns height by +/- 50%
icon: Icon(Icons.keyboard_arrow_down),hint: Text(
'${productentryController.selectedItem.toString()}'),value: catagory,items: productentryController.catagories
.map((CatagoryModel item) {
return DropdownMenuItem(
value: item.catagoryname,child: Text(item.catagoryname),);
}).toList(),onChanged: (selectedItem) {
productentryController.changeSelect(Item);
catagory=productController.selectedItem.value;
}),)),);
},]),);
}
}
解决方法
像这样创建一个下拉选择器类并在你想要的地方使用它
class DropdownPickerGetX extends StatelessWidget {
DropdownPickerGetX(
{this.menuOptions,this.selectedOption,this.onChanged});
final List<dynamic> menuOptions;
final String selectedOption;
final void Function(String) onChanged;
@override
Widget build(BuildContext context) {
//if (Platform.isIOS) {}
return DropdownButton<String>(
items: menuOptions
.map((data) => DropdownMenuItem<String>(
child: Row(
mainAxisAlignment: MainAxisAlignment.start,children: <Widget>[
Icon(data.icon),SizedBox(width: 10),Text(
data.value,),],value: data.key,))
.toList(),value: selectedOption,onChanged: onChanged);
}
}
,
这就是我在下拉菜单中使用 GetX 的方式
我正在使用具有 MVC 结构的 GetX、用于列表或响应等的模型、用于在 UI 中显示数据的视图、用于处理业务逻辑的控制器。首先查看我在此示例中使用的示例响应。
响应
{
"users": [
{
"user_type_id": "0","user_type": "USER 1"
},{
"user_type_id": "1","user_type": "USER 2"
},{
"user_type_id": "2","user_type": "USER 3"
},{
"user_type_id": "3","user_type": "USER 4"
}
]
}
现在,在您的模型类中。比方说 -> dropdown_model.dart
这是您列表的模型,它将显示在下拉列表中。您可以在 quicktype.io
为您的回复创建模型import 'dart:convert';
DropdownModel dropdownModelFromJson(String str) => DropdownModel.fromJson(json.decode(str));
String dropdownModelToJson(DropdownModel data) => json.encode(data.toJson());
class DropdownModel {
DropdownModel({
this.users,});
List<User> users;
factory DropdownModel.fromJson(Map<String,dynamic> json) => DropdownModel(
users: List<User>.from(json["users"].map((x) => User.fromJson(x))),);
Map<String,dynamic> toJson() => {
"users": List<dynamic>.from(users.map((x) => x.toJson())),};
}
class User {
User({
this.userTypeId,this.userType,});
String userTypeId;
String userType;
factory User.fromJson(Map<String,dynamic> json) => User(
userTypeId: json["user_type_id"],userType: json["user_type"],dynamic> toJson() => {
"user_type_id": userTypeId,"user_type": userType,};
}
现在,在您的控制器类中。比方说 -> register_controller.dart
//Make sure to import required packages
class RegisterController extends GetxController{
//Declaration and initializations
DropdownModel model;
Rx<List<User>> userTypeListM = Rx<List<User>>();
Rx<User>selectedUserType = Rx<User>();
Rx<String>userTypeId = Rx<String>();
//this is used,just to avoid any null error until list is fetched
var toggle = false.obs;
//This is a sample api call,fetch your data/list and assign list to RxList,//Your API Call goes right in this method
getList() async {
String data = await rootBundle.loadString('assets/user_type.json');
model = dropdownModelFromJson(data);
//if in case userTypeListM.value doesn't work then try userTypeListM.assignAll(model.users)
userTypeListM.value = model.users;
toggle.value = true;
}
//Call getList() in onInit() method
@override
void onInit() {
// TODO: implement onInit
super.onInit();
getList();
}
onSelectionChange(User value){
selectedUserType.value = value;
userTypeId.value = value.userTypeId;
}
}
现在,在您的 View 类中。比方说 -> register_view.dart
//Make sure to import required packages
class RegisterPage extends StatelessWidget{
final registerController = Get.put(RegisterController());
@override
Widget build(BuildContext context) {
return Scaffold(
body:Center(
child:Row(
children:[
Expanded(
flex:1,child: Container(
//color: Colors.white,margin: EdgeInsets.only(left: 15,right: 15,top: 16,bottom: 0),padding: EdgeInsets.symmetric(vertical: 5,horizontal: 8),decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),color: Colors.white,boxShadow: [
BoxShadow(
color: CupertinoColors.lightBackgroundGray,spreadRadius: 5,blurRadius: 25,offset: Offset(5,5),]
),child: Column(
/* crossAxisAlignment: CrossAxisAlignment.center,mainAxisAlignment: MainAxisAlignment.center,*/
children: <Widget>[
Obx(()=> registerController.toggle.value
? DropdownButton(
value: registerController.selectedUserType!=null ? registerController.selectedUserType.value: null,items: registerController.userTypeListM.value
.map<DropdownMenuItem<User>>((User value) {
return DropdownMenuItem<User>(
value: value,child: Text(value.userType.toString()),);
}).toList(),onChanged: (User value){
registerController.selectedUserType.value = value;
registerController.userTypeId.value = value.userTypeId;
registerController.update();
},underline: Container(color: Colors.transparent,hint: Text("Select value from dropdown"),isExpanded: true,)
: Container()
)
],)
),]
),)
);
}
}
就是这样!。它应该适用于下拉列表中的任何自定义模型。