我正在做flutter 婴儿名字代码实验室,并正在实施 firestore 事务以纠正竞争条件。如果我发送垃圾邮件名称,将会导致错过投票和 IllegalStateException。
我想在事务完成时从 onTap 中禁用 ListTile,然后在事务更新后重新启用它。
我尝试在事务中设置状态,但这不起作用。代码如下。
child: ListTile(
title: Text(record.name),
trailing: Text(record.votes.toString()),
onTap: () => Firestore.instance.runTransaction((transaction) async {
final freshSnapshot = await transaction.get(record.reference);
final fresh = Record.fromSnapshot(freshSnapshot);
await transaction.update(record.reference, {'votes': fresh.votes + 1});
///DOES NOT WORK
setState(() {
enabled: false
});
///
}),
Run Code Online (Sandbox Code Playgroud)
我尝试了这里的建议之一,但这也不起作用。似乎 _isEnableTile 布尔值的状态被重置,即使我从未将其设置回 true。一种有效的方法是将 _isEnableTile 设置为字段(即在类级别),不幸的是,这会导致所有列表图块通过“enabled”参数被禁用。
Widget _buildListItem(BuildContext context, DocumentSnapshot data) {
bool _isEnableTile = true;
final record = Record.fromSnapshot(data);
return Padding(
key: ValueKey(record.name),
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(5.0),
),
child: ListTile(
title: Text(record.name),
trailing: Text(record.votes.toString()),
onTap: () async {
print(_isEnableTile);
if (_isEnableTile) {
_isEnableTile = false;
print('doing it');
await Firestore.instance.runTransaction((transaction) async {
final freshSnapshot = await transaction.get(record.reference);
final fresh = Record.fromSnapshot(freshSnapshot);
await transaction
.update(record.reference, {'votes': fresh.votes + 1});
});
} else {
print('hmmm not doing it');
}
},
),
),
);
}
Run Code Online (Sandbox Code Playgroud)
上述代码的预期行为是能够点击一次,然后永远无法再次点击,因为 _isEnableTile 永远不会切换回 true。不是这种情况。_isEnableTile 不断重置为 true(很可能在 onTap 完成后立即重置)。
编辑:不幸的是,您不能使用启用来切换启用状态,因为由于某种原因它在 ListTile 中是最终的。
在这个问题上花了太长时间之后。我已经设法弄清楚了。
由于数据的预期用途,您需要在更广泛的范围内管理启用状态,并与从 Firebase 获取的实际数据分开。
您可以在下面的代码中看到预期的行为:
import 'package:baby_names/my_list_tile.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Baby Names',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Baby Names Codelabs'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<Record> _items = new List<Record>();
Map<String, bool> eState = new Map<String, bool>();
_MyHomePageState() {
Firestore.instance.collection('baby').snapshots().listen((data) {
_items.removeRange(0, _items.length);
setState(() {
data.documents.forEach((doc) => _items.add(Record.fromSnapshot(doc)));
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: ListView.builder(
padding: const EdgeInsets.only(top: 20.0),
itemCount: _items.length,
itemBuilder: (context, index) => _buildListItem(context, index)));
}
Widget _buildListItem(BuildContext context, int index) {
var record = _items[index];
var e = eState[record.name] == null ? true : eState[record.name];
return Padding(
key: ValueKey(record.name),
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(5.0),
),
child: ListTile(
title: Text(record.name),
trailing: Text(record.votes.toString()),
enabled: e,
onTap: () =>
Firestore.instance.runTransaction((transaction) async {
setState(() {
eState[record.name] = false;
});
final freshSnapshot =
await transaction.get(record.reference);
final fresh = Record.fromSnapshot(freshSnapshot);
await transaction
.update(record.reference, {'votes': fresh.votes + 1});
setState(() {
eState[record.name] = true;
});
})),
));
}
}
class Record {
final String name;
final int votes;
final DocumentReference reference;
Record.fromMap(Map<String, dynamic> map, {this.reference})
: assert(map['name'] != null),
assert(map['votes'] != null),
name = map['name'],
votes = map['votes'];
Record.fromSnapshot(DocumentSnapshot snapshot)
: this.fromMap(snapshot.data, reference: snapshot.reference);
@override
String toString() => "Record<$name:$votes>";
}
Run Code Online (Sandbox Code Playgroud)