Flutter-FutureBuilder-搜索

时间:2020-02-17 13:36:19

标签: flutter

我正在使用FuturBuilder获取用户列表。我通过futur:fetchpost()通过API吸引用户。在本专栏的开头,我实现了一个搜索栏。那么如何实现我的搜索栏正在搜索?

Container(
        child: FutureBuilder(
          future: fetchPost(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            if(snapshot.connectionState == ConnectionState.waiting) {
              return Container(
                child: ...CircularPro..(),
                ),

            } else {
              return Container(
                child: Column(
                  children: <Widget>[
                    Padding(
                      child: TextField(
                        onChanged: (value) {

                        },
                        controller: searchController,
                        decoration: InputDecoration(
                          prefixIcon: Icon(Icons.search),
                        ),

                      ),
                    ),
                    Expanded(
                      child: ListView.builder(
                        itemCount: snapshot.data.length,
                        itemBuilder: (BuildContext context, int index) {
                          return ListTile(  
                            title: Text(
                              "[" + 
                              snapshot.data[index].id + "] " + 
                              snapshot.data[index].firstname + " " +
                              snapshot.data[index].lastname
                            ),
                            subtitle: Text(snapshot.data[index].email),


1 个答案:

答案 0 :(得分:3)

您需要在ListView上获取一些条件变量,然后在搜索栏的Submit事件中设置该变量的值,然后在窗口小部件setState()上进行设置。

String searchString = "";


TextField(
                        onChanged: (value) {
                          setState((){
                             searchString = value; 
                          });

                        },
                        controller: searchController,
                        decoration: InputDecoration(
                          prefixIcon: Icon(Icons.search),
                        ),

                      ),

 ListView.builder(
                        itemCount: snapshot.data.length,
                        itemBuilder: (BuildContext context, int index) {
                          return snapshot.data[index].firstname.contains(searchString)? ListTile(  
                            title: Text(
                              "[" + 
                              snapshot.data[index].id + "] " + 
                              snapshot.data[index].firstname + " " +
                              snapshot.data[index].lastname
                            ),
                            subtitle: Text(snapshot.data[index].email),
...

:Container(),