无法添加到onTap中的集合中

时间:2019-05-21 20:13:57

标签: dart flutter

我在Flutter上遵循Write Your First App tutorial, part 2(在布局和标识符命名方面有些自由),但是遇到了麻烦。我似乎无法使onTap正常工作。这是我的代码。

import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: SuggestedNamesPage(title: 'Suggested Names'),
    );
  }
}

class SuggestedNamesPage extends StatefulWidget {
  SuggestedNamesPage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _SuggestedNamesPageState createState() => _SuggestedNamesPageState();
}

class _SuggestedNamesPageState extends State<SuggestedNamesPage> {
  final _suggestions = <WordPair>[];
  final _fave = Set<WordPair>();

  Widget _buildSuggestions() {
    return ListView.builder(
      padding: const EdgeInsets.all(16.0),
      itemBuilder: (context, i) {
        if (i.isOdd) return Divider();
        final int n = i ~/ 2;
        if (n >= _suggestions.length) {
          _suggestions.addAll(generateWordPairs().take(10));
        }
        return _buildRow(_suggestions[n]);
      });
  }

  Widget _buildRow(WordPair pair) {
    final isFavorite = _fave.contains(pair);
    return  ListTile(
      title: Text(
        pair.asPascalCase,
        style: TextStyle(
          fontSize: 18.0,
        ),
      ),
      trailing: Icon(
        isFavorite ? Icons.favorite : Icons.favorite_border,
        color : isFavorite ? Colors.red : null,
      ),
      onTap: () {
        setState(() {
          if (isFavorite) {
            _fave.add(pair);
          } else {
            _fave.remove(pair);
          }
        });
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Suggested Names'),
      ),
      body: _buildSuggestions(),
    );
  }

}

个人ListTile正在获得墨水飞溅效果,但没有添加任何内容到_fave。我想念什么吗?

我还要指出,example code中也缺少onTap

此外,这是flutter --version的输出:

Flutter 1.5.4-hotfix.2 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 7a4c33425d (3 weeks ago) • 2019-04-29 11:05:24 -0700
Engine • revision 52c7a1e849
Tools • Dart 2.3.0 (build 2.3.0-dev.0.5 a1668566e5)

1 个答案:

答案 0 :(得分:0)

if语句正在检查收藏夹,然后将其添加,并且由于该对永远不在收藏夹中,因此永远不会添加。

您应该像这样切换.add.remove方法:

setState(() {
  if (isFavorite) {
    _fave.remove(pair);
  } else {
    _fave.add(pair);
  }
});