更新所以行'final CollectionReference golfCartCollection = FirebaseFirestore.instance.collection('golf_cart');' 作業并提供資料但是如果我將'CollectionReference'更改為'Query'它會在代碼中進一步分解'//將新產品持久化到Firestore //等待golfCartCollection.add({'帶有.add錯誤要求提取方法和' // 更新產品 // await golfCartCollection.doc(documentSnapshot!.id)' 帶有 .doc 錯誤,要求提取方法。結束更新
行。我正在“自學”顫抖,已經走到了這一步。遵循教程、示例等,我現在可以通過 ListViews 顯示資訊,但是使用示例并將它們組合起來,因為我有一個問題。我無法對 ListView 進行排序。
如果我將“CollectionReference”更改為“Query”,正如許多人所指出的那樣,我會失去功能并進一步得到錯誤。
請查看代碼,如果可能的話將我推向正確的路徑。一如既往,我感謝任何和所有的幫助。
順便說一句,這是在 iOS 和 Android 模擬器上使用 VSCode 的帶有 Firebase 的 Flutter。我將附上 ListView 螢屏的螢屏截圖。
const GolfCartdbScreen({Key? key}) : super(key: key);
@override
_GolfCartdbScreenState createState() => _GolfCartdbScreenState();
}
class _GolfCartdbScreenState extends State<GolfCartdbScreen> {
static final DateTime now = DateTime.now();
// // YES there are many text controllers. Its a registration for golf carts and need this info. Will add the remaining controllers when I get it working // //
final _date = TextEditingController(text: '$now');
late bool _active;
final addCityController = TextEditingController(text: 'Welaka');
final addStateController = TextEditingController(text: 'FL');
final TextEditingController addStreetController = new TextEditingController();
final addZipController = TextEditingController(text: '32193');
final TextEditingController businessNameController =
new TextEditingController();
final TextEditingController dateInitialController =
new TextEditingController();
final TextEditingController dateRenewController = new TextEditingController();
final TextEditingController emailController = new TextEditingController();
final TextEditingController firstNameController = new TextEditingController();
final TextEditingController lastNameController = new TextEditingController();
final TextEditingController phoneNumberController =
new TextEditingController();
final TextEditingController regNumberController = new TextEditingController();
final TextEditingController timeStampController = new TextEditingController();
final TextEditingController vehColorController = new TextEditingController();
final TextEditingController vehMakeController = new TextEditingController();
final TextEditingController vehModelController = new TextEditingController();
final TextEditingController vinNumberController = new
// // // THE TWO LINES BELOW WORK TO PROVIDE THE DATA HOWEVER IF I CHANGE TO QUERY HAVE ISSUE FURTHER DOWN WITH 'await golfCartCollection.add' AND ' await golfCartCollection.doc(documentSnapshot!.id)' WITH ADD and DOC HAVING ERRORS // // //
final CollectionReference golfCartCollection =
FirebaseFirestore.instance.collection('golf_cart');
// This function is triggered when the floating button or one of the edit buttons is pressed
// Adding a product if no documentSnapshot is passed
// If documentSnapshot != null then update an existing product
Future<void> _createOrUpdate([DocumentSnapshot? documentSnapshot]) async {
String action = 'create';
if (documentSnapshot != null) {
action = 'update';
addStreetController.text = documentSnapshot['addStreet'].toString();
firstNameController.text = documentSnapshot['firstName'].toString();
lastNameController.text = documentSnapshot['lastName'].toString();
}
await showModalBottomSheet(
isScrollControlled: true,
context: context,
builder: (BuildContext ctx) {
return Padding(
padding: EdgeInsets.only(
top: 20,
left: 20,
right: 20,
bottom: MediaQuery.of(ctx).viewInsets.bottom 20),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
controller: firstNameController,
decoration: const InputDecoration(labelText: 'Fisrt Name'),
),
TextField(
controller: lastNameController,
decoration: const InputDecoration(
labelText: 'Last Name',
),
),
TextField(
controller: addStreetController,
decoration: const InputDecoration(
labelText: 'Address: Street',
),
),
const SizedBox(
height: 20,
),
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: CustomColors.welakaoneBlack,
),
child: Text(action == 'create' ? 'Create' : 'Update'),
onPressed: () async {
final String? firstName = firstNameController.text;
final String? lastName = lastNameController.text;
final String? addStreet = addStreetController.text;
if (firstName != null &&
lastName != null &&
addStreet != null) {
if (action == 'create') {
// Persist a new product to Firestore
await golfCartCollection.add({
"firstName": firstName,
"lastName": lastName,
"addStreet": addStreet
});
}
if (action == 'update') {
// Update the product
await golfCartCollection
.doc(documentSnapshot!.id)
.update({
"firstName": firstName,
"lastName": lastName,
"addStreet": addStreet
});
}
// Clear the text fields
firstNameController.text = '';
lastNameController.text = '';
addStreetController.text = '';
// Hide the bottom sheet
Navigator.of(context).pop();
}
},
)
],
),
);
});
}
// Deleteing a product by id
Future<void> _deleteProduct(String productId) async {
await golfCartCollection.doc(productId).delete();
// Show a snackbar
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('You Have Successfully Deleted The Registration.'),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
systemOverlayStyle: SystemUiOverlayStyle.dark,
backgroundColor: CustomColors.welakaoneBlack,
title: AppBarTitle(),
leading: Builder(
builder: (context) {
return IconButton(
onPressed: () {
Scaffold.of(context).openDrawer();
},
icon: Icon(Icons.menu),
);
},
),
actions: <Widget>[
Builder(
builder: (context) {
return IconButton(
onPressed: () {
Scaffold.of(context).openEndDrawer();
},
icon: Icon(Icons.person),
);
},
),
],
),
drawer: new MyDrawer(),
endDrawer: new MyEndDrawer(
uid: '',
),
// Using StreamBuilder to display all products from Firestore in real-time
body: new Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [
CustomColors.welakaoneBlack,
CustomColors.welakaoneBlueDark,
],
begin: FractionalOffset(0.0, 0.0),
end: FractionalOffset(1.6, 1.0),
stops: [0.3, 1.0],
tileMode: TileMode.clamp,
),
),
child: StreamBuilder(
stream: golfCartCollection.snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> streamSnapshot) {
if (streamSnapshot.hasData) {
return ListView.builder(
itemCount: streamSnapshot.data!.docs.length,
itemBuilder: (context, index) {
final DocumentSnapshot documentSnapshot =
streamSnapshot.data!.docs[index];
return Card(
color: Colors.transparent,
margin: const EdgeInsets.all(0),
child: ListTile(
title: Text(
documentSnapshot['firstName'].toString()
' '
documentSnapshot['lastName'.toString()],
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: CustomColors.welakaoneWhite,
),
),
subtitle: Text(
documentSnapshot['addStreet'].toString(),
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.normal,
color: CustomColors.welakaoneWhite,
),
),
trailing: SizedBox(
width: 100,
child: Row(
children: [
// Press this button to edit a single product
IconButton(
icon: const Icon(Icons.edit),
color: CustomColors.welakaoneYellow,
onPressed: () =>
_createOrUpdate(documentSnapshot)),
// This icon button is used to delete a single product
IconButton(
icon: const Icon(Icons.delete),
color: CustomColors.welakaoneYellow,
onPressed: () =>
_deleteProduct(documentSnapshot.id)),
],
),
),
),
);
},
);
}
return const Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(
CustomColors.welakaoneYellow,
),
),
);
},
),
),
// Add new product
floatingActionButton: FloatingActionButton(
backgroundColor: CustomColors.welakaoneYellow,
onPressed: () => _createOrUpdate(),
child: const Icon(
Icons.add,
color: CustomColors.welakaoneBlueDark,
),
),
);
}
}
[![enter image description here][1]][1] ```
[1]: https://i.stack.imgur.com/5STK5.jpg
uj5u.com熱心網友回復:
要對串列視圖進行排序,請在此處添加 order-by 子句:
...
child: StreamBuilder(
stream: golfCartCollection.orderBy('lastName').snapshots(),
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/411320.html
標籤:
下一篇:對文本檔案中的行子組進行排序
