如何根据项目包含的数据过滤列表

时间:2019-06-04 07:18:49

标签: flutter dart

我正在尝试实现一种搜索方法。 我有一个清单,可以说:

List<Users> _users = [user1, user2, user3];

我的课是:

class User {
  final String name;
  final String id;
}

列表中的项目是:

var user1 = User(name: "Bob", id: 1);
var user2 = User(name: "Alice", id: 2);
var user3 = User(name: "Joe", id: 3);

例如,如何根据用户名过滤列表?

2 个答案:

答案 0 :(得分:2)

使用where

List<User> filtered = _users.where((user) => user.name == "Joe" ).toList();

答案 1 :(得分:1)

正如其他人所述,您可以使用where()或其他方法。您可以read the doc for more

简单演示:

import 'package:flutter/material.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: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  List<User> _users = [
    User(name: "Bob", id: 1),
    User(name: "Alice", id: 2),
    User(name: "Joe", id: 3),
  ];
  List<User> duplicate = [];
  TextEditingController _textController;

  @override
  void initState() {
    _textController = TextEditingController();
    duplicate = _users;
    super.initState();
  }

  @override
  void dispose() {
    _textController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: TextField(
          controller: _textController,
          onChanged: (String value) {
            if (value != "") {
              setState(() {
                _users = _users.where((test) => test.name.toLowerCase().contains(value)).toList(); 
              });
            } else {
              setState(() {
                _users = duplicate; 
              });
            }
          },
        ),//Just to show an demo, you can use flutter search instead this
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: _users.map((user) => Card(child: Text(user.name))).toList(),
        ),
      ),
    );
  }
}

class User {
  final String name;
  final int id;

  User({this.id, this.name});
}