除了在颤动中创建两条相同的线以外,传递状态的更好方法

时间:2018-06-21 09:59:39

标签: dart flutter

因此,我正在使用flutter的website做本教程,然后修改该教程的代码以在有状态的小部件上添加删除功能。我认为这是多余的事情(注释1至5):

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

void main() {
  runApp(new MyApp());
}

class SavedWords extends StatefulWidget {
  final Set<WordPair> _saved; // 1
  SavedWords(this._saved); // 2
  @override
  createState() => SavedWordState(_saved); // 3
}

class SavedWordState extends State<SavedWords> {
  Set<WordPair> _saved; // 4
  SavedWordState(this._saved); // 5

  @override
  Widget build(BuildContext context) {
    final tiles = _saved.map(
      (pair) {
        return new ListTile(
          title: new Text(
            pair.asPascalCase,
          ),
          trailing: new Icon(Icons.delete),
          onTap: () {
            setState(() {
              _saved.remove(pair);
            });
          },
        );
      },
    );
    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),
    );
  }
}

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

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

  final _saved = new Set<WordPair>();
  final _biggerFont = const TextStyle(fontSize: 18.0);
  @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(),
    );
  }

  void _pushSaved() {
    Navigator.of(context).push(
      new MaterialPageRoute(
        builder: (context) {
          return new SavedWords(_saved);
        },
      ),
    );
  }

  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 Icon(
        alreadySaved ? Icons.favorite : Icons.favorite_border,
        color: alreadySaved ? Colors.red : null,
      ),
      onTap: () {
        setState(() {
          if (alreadySaved) {
            _saved.remove(pair);
          } else {
            _saved.add(pair);
          }
        });
      },
    );
  }
}

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

这只是1个视图,想像一下如果有很多视图,是否有更好的方法来做到这一点?

1 个答案:

答案 0 :(得分:2)

您不应在State<T>子类上具有自定义构造函数。

所以你做不到

class SavedWordState extends State<SavedWords> {
  Set<WordPair> _saved; // 4
  SavedWordState(this._saved); // 5

@override
createState() => SavedWordState(_saved); // 3

相反,State<T>具有T widget属性,该属性用于从StatefulWidget子类中获取字段。

因此,在您的State<T>中,您可以执行以下操作:

class SavedWords extends StatefulWidget {
  final Set<WordPair> saved;
  SavedWords({ this.saved });

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

...

  @override
  Widget build(BuildContext context) {
    final tiles = widget.saved.map(