当TextField值更改时,Flutter FutureBuilder刷新

时间:2020-02-08 09:44:45

标签: flutter dart flutter-layout flutter-dependencies

_futureData函数中获取值后,FutureBuilder将用于_loadPhobias()

entry_screen.dart

Future _futureData;
final TextEditingController _textEditingController = TextEditingController();

_loadPhobias()函数似乎没有任何问题。

entry_screen.dart

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(
        // When the value is changed, the value returned from the _loadPhobias will also change. So I want the FutureBuilder to be rebuilt.
        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()回调参数返回了Future。

_EntryScreenState#51168上的setState()方法通过返回Future的闭包或方法来调用。也许它被标记为“异步”。

与其在调用setState()的过程中执行异步工作,不如先执行工作(不更新窗口小部件状态),然后在对setState()的调用中进行同步更新状态。)

2 个答案:

答案 0 :(得分:4)

首先要注意的是,您提到要在每次文本更改时都“重建”应用程序。为此,您应该使用StreamBuilderFutureBuilder只能使用一次,就像火灾和遗忘事件或JavaScript中的Promise。

HereStreamBuilderFutureBuilder之间的比较。

这是重构代码以使用StreamBuilder的方式。

main.dart

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyAppScreen(),
    );
  }
}

class MyAppScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MyAppScreenState();
  }
}

class MyAppScreenState extends State<MyAppScreen> {
  StreamController<List<String>> _phobiasStream;

  final TextEditingController _textEditingController = TextEditingController();

  void _loadPhobias() async =>
      await rootBundle.loadString('lib/phobia.txt').then((phobias) {
        List<String> _listOfSortedPhobias = [];
        for (String i in LineSplitter().convert(phobias)) {
          for (String t in _textEditingController.text.split('')) {
            if (i.split('-').first.toString().contains(t)) {
              _listOfSortedPhobias.add(i);
            }
          }
        }
        _phobiasStream.add(_listOfSortedPhobias);
      });

  @override
  void initState() {
    super.initState();
    _phobiasStream = StreamController<List<String>>();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: TextField(
          controller: _textEditingController,
          onChanged: (text) {
            print("Text $text");
            _loadPhobias();
          },
        ),
      ),
      body: StreamBuilder(
        stream: _phobiasStream.stream,
        builder: (context, snapshot) {
          return snapshot.hasData
              ? Container(
                  height: 300,
                  child: ListView.builder(
                    itemCount: snapshot.data.length,
                    itemBuilder: (context, index) {
                      print("Data ${snapshot.data[index]}");
                      return Text(snapshot.data[index]);
                    },
                  ),
                )
              : Center(
                  child: CircularProgressIndicator(),
                );
        },
      ),
    );
  }
}

如上面的代码所示,我消除了for循环内不必要的文本更改回调。

lib / phobia.txt

test1-test2-test3-test4-test5

让我知道这是否是预期的情况。

希望这会有所帮助。

答案 1 :(得分:0)

可以在错误消息的第三行中推断出解决方案:

与其在调用setState()的过程中执行异步工作,不如先执行工作(不更新窗口小部件状态),然后在对setState()的调用中进行同步更新状态。)

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

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

可以写为:

onChanged: (text) async {
    var phobias = _loadPhobias();
    setState(() {
        _futureData = phobias;
    });
},