flutter 如何从可搜索下拉列表中按名称而不是按ID搜索项目?

jdzmm42g  于 2023-10-22  发布在  Flutter
关注(0)|答案(2)|浏览(147)

如何从可搜索下拉列表中按名称而不是按ID搜索项目?

SearchableDropdown(items:_vagasDisponiveis.map((item) {
            return new DropdownMenuItem(
              child: Text(item.v_n),
              value: item.v_id
            );
          }
        ).toList(),
    isExpanded: true,
    value: vaga_id,
    isCaseSensitiveSearch: true,
    searchHint: new Text('Select ', style: new TextStyle(fontSize: 20)),
    onChanged: (value) {
      setState(() {
        vaga_id = value;
    });
  },
)

示例:https://pub.dev/packages/searchable_dropdown

oxiaedzo

oxiaedzo1#

您必须覆盖类的toString(),以便它可以搜索id和name
因为SearchableDropdown的源代码使用item.value.toString()
当你传递类名时,它将变成I/flutter ( 7352): Instance of 'VagasDisponivei'
你可以复制粘贴下面运行完整的代码
代码片段

class VagasDisponivei {
  String v_n;
  String v_id;

  VagasDisponivei({this.v_n, this.v_id});

  @override
  String toString() {
    return '${v_n} ${v_id}';
  }
}

SearchableDropdown(
              items: _vagasDisponiveis.map((item) {
                return new DropdownMenuItem<VagasDisponivei>(
                    child: Text(item.v_n), value: item);
              }).toList(),
              isExpanded: true,
              value: selectedValue,
              isCaseSensitiveSearch: true,
              searchHint: new Text(
                'Select ',
                style: new TextStyle(fontSize: 20),
              ),
              onChanged: (value) {
                setState(() {
                  selectedValue = value;
                  print(selectedValue);
                });
              },
            ),

工作演示

完整代码

import 'package:flutter/material.dart';
import 'package:searchable_dropdown/searchable_dropdown.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @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 VagasDisponivei {
  String v_n;
  String v_id;

  VagasDisponivei({this.v_n, this.v_id});

  @override
  String toString() {
    return '${v_n} ${v_id}';
  }
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  List<VagasDisponivei> _vagasDisponiveis;
  String vaga_name;
  VagasDisponivei selectedValue;
  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _vagasDisponiveis = [
      VagasDisponivei(v_id: "1", v_n: "abc"),
      VagasDisponivei(v_id: "2", v_n: "def"),
      VagasDisponivei(v_id: "3", v_n: "dgg"),
    ];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            SearchableDropdown(
              items: _vagasDisponiveis.map((item) {
                return new DropdownMenuItem<VagasDisponivei>(
                    child: Text(item.v_n), value: item);
              }).toList(),
              isExpanded: true,
              value: selectedValue,
              isCaseSensitiveSearch: true,
              searchHint: new Text(
                'Select ',
                style: new TextStyle(fontSize: 20),
              ),
              onChanged: (value) {
                setState(() {
                  selectedValue = value;
                  print(selectedValue);
                });
              },
            ),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

SearchableDropdown的代码片段

if(widget.isCaseSensitiveSearch){
        print(item.value.toString());
        isContains = item.value.toString().contains(keyword);
      }
eni9jsuy

eni9jsuy2#

我正在使用搜索:联系我们
下面是我的代码,它查找具有名称的项目,并在值中设置它们的ID。

import 'package:dropdown_search/dropdown_search.dart';
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,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      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> {
  KeyValueModel selectedValue;
  String hello;
  TextEditingController v = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: SingleChildScrollView(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              DropdownSearch<KeyValueModel>(
                  mode: Mode.DIALOG,
                  showSelectedItem:false,
                  items: [KeyValueModel(itemId: "123",itemName: "mohit"),KeyValueModel(itemId: "124",itemName: "hello"),KeyValueModel(itemId: "125",itemName: "hey")],
                  itemAsString: (KeyValueModel u) => u.itemName,
                  hint: "select",
                  onChanged: (value){
                    v.text = value.itemId.toString();
                    print(value.itemId);
                  },
                  showSearchBox: true,
                  filterFn: (instance, filter){
                    if(instance.itemName.contains(filter)){
                      print(filter);
                      return true;
                    }
                    else{
                      return false;
                    }
                  },
                  popupItemBuilder: (context,KeyValueModel item,bool isSelected){
                    return Container(
                      margin: EdgeInsets.symmetric(horizontal: 8),
                      decoration: !isSelected
                          ? null
                          : BoxDecoration(
                        border: Border.all(color: Theme.of(context).primaryColor),
                        borderRadius: BorderRadius.circular(5),
                        color: Colors.white,
                      ),
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text(item.itemName),
                      ),
                    );
                  },
                 ),
            ],
          ),
        ),
      ),
    );
  }
}
class KeyValueModel{
  String itemName;
  String itemId;
  KeyValueModel({this.itemName,this.itemId});
}

相关问题