当文本字段值更改时,将使将来的构建器刷新

问题描述 投票:0回答:1
class _EntryScreenState extends State<EntryScreen> {

从_loadPhobias函数获取值后,_futureData将用于futurebuilder

  Future _futureData;

  final TextEditingController _textEditingController = TextEditingController();

_ loadPhobias()没问题

  Future<List<String>> _loadPhobias() async =>
      await rootBundle.loadString('assets/phobias.txt').then((phobias) {
        List _listOfAllPhobias = [];
        List<String> _listOfSortedPhobias = [];

         _textEditingController.addListener(() {
            ...................
          }); 
        }
        return _listOfSortedPhobias;
      });

  @override
  void initState() {
    super.initState();
    _futureData = _loadPhobias();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: TextField(

更改值时,从_loadPhobias返回的值将更改。因此,我希望对futurebuilder进行重建。

          onChanged: (text) { setState(() => _futureData =  _loadPhobias()) },
        ),
      ),
      body: FutureBuilder(
          future: _futureData,
          builder: (context, snapshot) {
            return snapshot.hasData
                ? ListView.builder(
                    itemCount: snapshot.data.length,
                    itemBuilder: (context, index) => Column(
                          children: <Widget>[
                            PhobiasCard(sentence: snapshot.data[index]),
                            )
                          ],
                        ))
                : Center(
                    child: CircularProgressIndicator(),
                  );
          },
        ),
      ),
    );
  }
}

**这是我得到的错误**

FlutterError (setState() callback argument returned a Future.
The setState() method on _EntryScreenState#51168 was called with a closure or method that returned a Future. Maybe it is marked as "async".
Instead of performing asynchronous work inside a call to setState(), first execute the work (without updating the widget state), and then synchronously update the state inside a call to setState().)
flutter dart flutter-layout flutter-dependencies
1个回答
0
投票

错误消息第三行中的解决方案:

Instead of performing asynchronous work inside a call to setState(), first execute the work (without updating the widget state), and then synchronously update the state inside a call to setState().)

因此,您必须在刷新窗口小部件之前执行该操作。您可以使用一个临时变量来保存异步工作的结果,并在setState方法中使用它:

      onChanged: (text) { setState(() => _futureData =  _loadPhobias()) },

将成为:

 onChanged: (text) async {
                var phobias = await _loadPhobias();
                setState(() {
                  _futureData = phobias;
                });
              },
© www.soinside.com 2019 - 2024. All rights reserved.