如何从自己的onTap中禁用ListTile?

时间:2019-01-10 11:12:33

标签: flutter

我正在做flutter baby names codelab,并且正在将交易实施到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
            });
            ///
          }),

我尝试了这里的建议之一,但也没有用。似乎_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');
                }
              },
            ),
          ),
        );
      }

以上代码的预期行为是能够一次点击,然后再也无法再次点击,因为_isEnableTile从未切换回true。不是这种情况。 _isEnableTile不断地重置为true(最有可能在onTap完成后立即重置)。

编辑: 不幸的是,由于某种原因,它不能在ListTile中最终使用,因此不能使用enabled来切换启用状态。

2 个答案:

答案 0 :(得分:1)

像这样拿一个标志

bool isEnableTile = true;

并设置为

onTap: (isEnableTile == true )? (Code+StateToChange "isEnableTile" to *false*) : null

答案 1 :(得分:0)

在这个问题上花了太长时间之后。我设法弄清楚了。

由于数据的预期用途,您需要在更大的范围内管理启用状态,并将其与从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>";
}