返回页面时,带有过滤器搜索页面的Flutter不断从查询中添加相同的列表视图

加斯·法比恩

我最近遵循了这个答案:Flutter中的Listview过滤器搜索,介绍如何使用搜索过滤器实现Flutter Listview。过滤器按照答案中的说明工作。每次我移出该特定页面然后再返回该问题时,列表视图中的结果都增加了一倍。当我再次走出页面并再次返回时,它的大小增加了两倍。

我知道我应该在离开列表视图页面时在某处清除列表,不确定您在哪里。下面是我遵循的示例代码。我的MySQL查询很简单。SELECT * FROM table_name。

import 'dart:async';

import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;

void main() => runApp(new MaterialApp(
  home: new HomePage(),
  debugShowCheckedModeBanner: false,
));

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => new _HomePageState();
}

class _HomePageState extends State<HomePage> {
  TextEditingController controller = new TextEditingController();

  // Get json result and convert it to model. Then add
  Future<Null> getUserDetails() async {
    final response = await http.get(url);
    final responseJson = json.decode(response.body);

    setState(() {
      for (Map user in responseJson) {
        _userDetails.add(UserDetails.fromJson(user));
      }
    });
  }

  @override
  void initState() {
    super.initState();

    getUserDetails();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Home'),
        elevation: 0.0,
      ),
      body: new Column(
        children: <Widget>[
          new Container(
            color: Theme.of(context).primaryColor,
            child: new Padding(
              padding: const EdgeInsets.all(8.0),
              child: new Card(
                child: new ListTile(
                  leading: new Icon(Icons.search),
                  title: new TextField(
                    controller: controller,
                    decoration: new InputDecoration(
                        hintText: 'Search', border: InputBorder.none),
                    onChanged: onSearchTextChanged,
                  ),
                  trailing: new IconButton(icon: new Icon(Icons.cancel), onPressed: () {
                    controller.clear();
                    onSearchTextChanged('');
                  },),
                ),
              ),
            ),
          ),
          new Expanded(
            child: _searchResult.length != 0 || controller.text.isNotEmpty
                ? new ListView.builder(
              itemCount: _searchResult.length,
              itemBuilder: (context, i) {
                return new Card(
                  child: new ListTile(
                    leading: new CircleAvatar(backgroundImage: new NetworkImage(_searchResult[i].profileUrl,),),
                    title: new Text(_searchResult[i].firstName + ' ' + _searchResult[i].lastName),
                  ),
                  margin: const EdgeInsets.all(0.0),
                );
              },
            )
                : new ListView.builder(
              itemCount: _userDetails.length,
              itemBuilder: (context, index) {
                return new Card(
                  child: new ListTile(
                    leading: new CircleAvatar(backgroundImage: new NetworkImage(_userDetails[index].profileUrl,),),
                    title: new Text(_userDetails[index].firstName + ' ' + _userDetails[index].lastName),
                  ),
                  margin: const EdgeInsets.all(0.0),
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  onSearchTextChanged(String text) async {
    _searchResult.clear();
    if (text.isEmpty) {
      setState(() {});
      return;
    }

    _userDetails.forEach((userDetail) {
      if (userDetail.firstName.contains(text) || userDetail.lastName.contains(text))
        _searchResult.add(userDetail);
    });

    setState(() {});
  }
}

List<UserDetails> _searchResult = [];

List<UserDetails> _userDetails = [];

final String url = 'my url address for mysql php query ';
class UserDetails {
  final int id;
  final String firstName, lastName, profileUrl;

  UserDetails({this.id, this.firstName, this.lastName, this.profileUrl = 'https://i.amz.mshcdn.com/3NbrfEiECotKyhcUhgPJHbrL7zM=/950x534/filters:quality(90)/2014%2F06%2F02%2Fc0%2Fzuckheadsho.a33d0.jpg'});

  factory UserDetails.fromJson(Map<String, dynamic> json) {
    return new UserDetails(
      id: json['id'],
      firstName: json['name'],
      lastName: json['username'],
    );
  }
}
香托

在添加新值之前,请尝试清除列表。

setState(() {
  _userDetails.clear();
  for (Map user in responseJson) {
    _userDetails.add(UserDetails.fromJson(user));
  }
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在 Django 视图页面中添加查询集月份和年份下拉列表过滤器

弹性搜索 更像这个带有过滤器的查询是添加结果

带有搜索过滤器的Flutter应用网格视图?

More_like_this带有过滤器的查询

在 vue 中的特定索引处返回带有过滤器对象的数组

如何从Python列表中创建不同的数据框(带有过滤器)

当执行参数化的N1QL查询时,Couchbase不使用带有过滤器的索引

AngularJS搜索过滤器不会在所有页面中搜索

如何查询表以获取在链接中没有记录的记录以及带有过滤器的记录

列表视图上的搜索过滤器在单击项目时返回错误结果

列表视图中的搜索过滤器在单击项目时返回错误值

带有布尔的弹性搜索过滤器查询返回无效结果

Wagtail / Django:查询过滤器仅返回用户具有访问权限的页面?

带有多个下拉过滤器的页面

仅当 mongodb 中的字段不为空时,mongodb 中是否有办法将过滤器/条件添加到现有过滤器

视图页面中的Django数据库过滤器

带有多个过滤器的Elasticsearch搜索查询

带有过滤器的搜索栏,以及使用Ionic 2的JSON数据

Laravel-带有过滤器和旧输入的搜索表单

在弹性搜索中使用带有过滤器的聚合

带有过滤器的多个字段的弹性搜索分组

SQL查询返回匹配任何或所有过滤器但不超过过滤器的行

带有过滤器的Android自动完成文本视图

在带有Cards的RecyclerView上添加搜索过滤器?

带有搜索过滤器的联系人列表

在应用带有搜索过滤器的dirPaginate时如何使用$ index访问列表项

带有过滤器选项的Google图表MySQL查询百分比

带有过滤器的ElasticSearch function_score查询

通过ForeignKey外部引用对带有过滤器的子查询进行了汇总