简体   繁体   English

Flutter 更改 TextEditController 上的 ListView 以进行搜索

[英]Flutter Change ListView on TextEditController for search

in the flutter code below I have to implement the search for the articles present in the list.在下面的 flutter 代码中,我必须实现对列表中存在的文章的搜索。 How do I make sure that when I change the TextEditController the listview is updated, the articles are loaded directly from a rest call on a node.js backend the articles are displayed however all I want to do is filter it with the TextEditController.如何确保当我更改 TextEditController 时更新列表视图,文章直接从 node.js 后端上的 rest 调用加载,但我想要做的就是使用 TextEditController 过滤它。

Dart Code: Dart 代码:

//Lista che contiene la lista degli articoli
List<Articolo> foods;
//Lista che contiene la lista delle categorie
List<Categoria> categories;
//Descrizione: funzione che esegue l'init dei valore della view
Future<bool> init() async {
  categories = await Categoria.caricamentoCategorie();
  foods = await Articolo.caricamento();
  return true;
}
class SearchScreen extends StatefulWidget {
  @override
  _SearchScreenState createState() => _SearchScreenState();
}
class _SearchScreenState extends State<SearchScreen>
    with AutomaticKeepAliveClientMixin<SearchScreen> {
  TextEditingController _searchControl = new TextEditingController();
  
  @override
  void initState() {
    super.initState();
  }
  
  _SearchScreenState(){
   BackButtonInterceptor.add(myInterceptor);
  }
  //Disabilito il bottone di back su android
  bool myInterceptor(bool stopDefaultButtonEvent, RouteInfo info) {
    return true;
  }
  Widget build(BuildContext context) {
    return FutureBuilder<bool>(
        future: init(),
        builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
          if (!snapshot.hasData) {
            return new Container();
          } else {
            super.build(context);
            return Padding(
              padding: EdgeInsets.fromLTRB(10.0, 0, 10.0, 0),
              child: ListView(
                children: <Widget>[
                  SizedBox(height: 10.0),
                  Card(
                    elevation: 6.0,
                    child: Container(
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(
                          Radius.circular(5.0),
                        ),
                      ),
                      child: TextField(
                        style: TextStyle(
                          fontSize: 15.0,
                          color: Colors.black,
                        ),
                        decoration: InputDecoration(
                          contentPadding: EdgeInsets.all(10.0),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(5.0),
                            borderSide: BorderSide(
                              color: Colors.white,
                            ),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: Colors.white,
                            ),
                            borderRadius: BorderRadius.circular(5.0),
                          ),
                          hintText: "Ricerca..",
                          suffixIcon: Icon(
                            Icons.search,
                            color: Colors.black,
                          ),
                          hintStyle: TextStyle(
                            fontSize: 15.0,
                            color: Colors.black,
                          ),
                        ),
                        maxLines: 1,
                        controller: _searchControl,
                      ),
                    ),
                  ),
                  SizedBox(height: 5.0),
                  Padding(
                    padding: EdgeInsets.all(20.0),
                    child: Text(
                      "Articoli",
                      style: TextStyle(
                        fontSize: 15,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                 
                  ListView.builder(
                    shrinkWrap: true,
                    primary: false,
                    physics: NeverScrollableScrollPhysics(),
                    itemCount: foods == null ? 0 : foods.length,
                    itemBuilder: (BuildContext context, int index) {
                      Articolo food = foods[index];
                      return ListTile(
                        title: Text(
                          food.getCodArt(),
                          style: TextStyle(
                        
                            fontWeight: FontWeight.w900,
                          ),
                        ),
                        leading: ClipRRect(
                  borderRadius: BorderRadius.circular(8.0),
                  child:  Image.network(
        food.getPathImmagine(),
        fit: BoxFit.cover,
        width: 100,
        height:100
    ),
                ),
                        trailing: Text(""),
                        subtitle: Row(
                          children: <Widget>[
                            
                            Text(
                              "Prezzo: "+food.getPrezzo(),
                              style: TextStyle(
                                color: Colors.red,
                                fontSize: 14,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ],
                        ),
                        onTap: () {
                          var view=new ProductDetails(food); 
                          Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => view));
                          
                        },
                      );
                    },
                  ),
                  SizedBox(height: 30),
                ],
              ),
            );
          }
        });
  }
  @override
  bool get wantKeepAlive => true;
}

You can do something like this.你可以做这样的事情。 Make your Future a variable that you can set when a user types something.使您的 Future 成为您可以在用户键入内容时设置的变量。 The search() method should be similar to your init() method, where it calls the service but with filtered results. search()方法应该类似于您的init()方法,它调用服务但过滤结果。

class _MyWidgetState extends State<MyWidget> {

  Future myFuture;

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

    myFuture = init();

    // Start listening to changes.
    _searchControl.addListener(_printLatestValue);
  }
 
  @override
  void dispose() {
       super.dispose();
       //don't forget to remove the listener to stop memory leaks
       _searchControl.removeListener(_onTextChanged);
 }

  _printLatestValue() {
     myFuture = search(_searchControl.text); //this will return your new future with your filtered list
     setState(() {  }); // this refreshes the view
  }

  Widget build(BuildContext context) {
    return FutureBuilder<bool>(
       future: myFuture, ... //this is a variable now instead of a direct method call

}

The first way is to listen directly by making a textcontroller listener.第一种方法是通过制作一个 textcontroller 监听器来直接监听。 In the second way, didChangeDependencies function dart special function runs the function you want to execute when something is changed instantly. In the second way, didChangeDependencies function dart special function runs the function you want to execute when something is changed instantly.

Options 1:选项 1:

 final _controller = TextEditingController();

 @override
 void initState() {
  super.initState();
  _controller.addListener(_onTextChanged);
 }

 @override
  void dispose() {
   super.dispose();
  _controller.removeListener(_onTextChanged);
  }

 void _onTextChanged() {
    search();

  }

Options 2:选项 2:

 final _controller = TextEditingController();
     VoidCallback _listener;

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

   if (_listener == null) {
    _listener = () {
      _search(_controller.text));
    };
   _controller.addListener(_listener);
 }
}

 @override
  void dispose() {
  super.dispose();
 _controller.removeListener(_listener);
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM