更改状态

时间:2018-03-01 04:21:23

标签: dart flutter

我刚刚开始使用Flutter,完成first codelab并试图为其添加一些简单的功能。

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Startup Name Generator',
      theme: new ThemeData(primaryColor: Colors.deepOrange),
      home: new RandomWords(),
    );
  }
}

class RandomWords extends StatefulWidget {
  @override
  createState() => new RandomWordsState();
}

class RandomWordsState extends State<RandomWords> {
  final _suggestions = <WordPair>[];

  final _biggerFont = new TextStyle(fontSize: 18.0);

  final _saved = new Set<WordPair>();

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Startup Name Generator'),
        actions: <Widget>[
          new IconButton(
            icon: new Icon(Icons.list),
            onPressed: _pushSaved,
          )
        ],
      ),
      body: _buildSuggestions(),
    );
  }

  Widget _buildSuggestions() {
    return new ListView.builder(
      padding: const EdgeInsets.all(16.0),
      itemBuilder: (context, i) {
        if (i.isOdd) return new Divider();

        final index = i ~/ 2;
        if (index >= _suggestions.length) {
          _suggestions.addAll(generateWordPairs().take(10));
        }
        return _buildRow(_suggestions[index]);
      },
    );
  }

  Widget _buildRow(WordPair pair) {
    final alreadySaved = _saved.contains(pair);
    return new ListTile(
        title: new Text(
          pair.asPascalCase,
          style: _biggerFont,
        ),
        trailing: new IconButton(
          icon: new Icon(alreadySaved ? Icons.favorite : Icons.favorite_border),
          color: alreadySaved ? Colors.red : null,
          onPressed: () {
            setState(() {
              if (alreadySaved) {
                _saved.remove(pair);
              } else {
                _saved.add(pair);
              }
            });
          },
        ));
  }

  void _pushSaved() {
    Navigator.of(context).push(
      new MaterialPageRoute(
        builder: (context) {
          final tiles = _saved.map(
            (pair) {
              return _buildRow(pair);

              // new ListTile(
              //   title: new Text(
              //     pair.asPascalCase,
              //     style: _biggerFont,
              //   ),
              // );
            },
          );
          final divided = ListTile
              .divideTiles(
                context: context,
                tiles: tiles,
              )
              .toList();

          return new Scaffold(
            appBar: new AppBar(
              title: new Text('Saved Suggestions'),
            ),
            body: new ListView(children: divided),
          );
        },
      ),
    );
  }
}

在保存建议屏幕中,我构建了与Sugestions屏幕相同的行。

在Saved Sugstions屏幕中,当您单击心脏图标时,元素将从保存的项目数组中删除,但不会重新渲染屏幕。

我在这里做错了什么?

谢谢!

1 个答案:

答案 0 :(得分:2)

<强>更新

实际上你的应用对我来说非常合适:/

因为您没有通过图标更改来传达状态更改。您已根据alreadySaved更改状态,请注意您管理的方式setState()

setState(() {
              if (alreadySaved) {
                _saved.remove(pair);
              } else {
                _saved.add(pair);
              }
            });

在上一个块中,您只是根据alreadySaved的布尔值删除或添加到您喜欢的列表中,并且您没有告诉setState更改其他任何内容。这就是为什么即使alreadySaved正在切换值

,以下内容也不会产生重新渲染
///These two lines do not know what is happening    
icon: new Icon(alreadySaved ? Icons.favorite : Icons.favorite_border),
              color: alreadySaved ? Colors.red : null,

所以你可以改为做以下

icon: new Icon(_whichIcon), //initialized var _whichIcon = Icons.favorite_border 
          color: _whichIconColor, //Initialized var _whichIconColor = Colors.transparent

您的setState将是:

setState(() {
              if (alreadySaved) {
                _saved.remove(pair);
                _whichIcon = Icons.favorite_border ;
                _whichIconColor = Colors.transparent; 
             } else {
                _saved.add(pair);
                _whichIcon = Icons.favorite ;
                _whichIconColor = Colors.red;
              }
            });

或者更简单,你可以这样做,并保持你的icon逻辑不变:

bool alreadySaved = false;

...

setState(() {
              if (_saved.contains(pair)) {
                _saved.remove(pair);
                alreadySaved = false;
              } else {
                _saved.add(pair);
                alreadySaved = true;
              }
            });