【问题标题】:how refresh listview on search flutter如何刷新搜索颤动的列表视图
【发布时间】:2020-12-12 11:42:33
【问题描述】:

您好,下面的 dart / flutter 代码在列表中进行搜索,但我无法在字段搜索完成后刷新列表。 从下面的代码可以看出,在dart flutter中对列表进行了搜索,然后外推数据,但是列表没有刷新 如何确保实现 dart 中列表的重新加载

颤振代码:

//Lista che contiene la lista degli articoli
List<Articolo> foods=new List<Articolo>();
//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();
    if(foods.length==0){
    print("\n Sono qui");
  foods = await Articolo.caricamento(null,null);
    }
  return true;
}

class SearchScreen extends StatefulWidget {
  @override
  _SearchScreenState createState() => _SearchScreenState();
}

class _SearchScreenState extends State<SearchScreen>
    with AutomaticKeepAliveClientMixin<SearchScreen> {
  TextEditingController _searchControl = new TextEditingController();
  Future myFuture;
  //final _controller = TextEditingController();
  VoidCallback _listener;

  _SearchScreenState(){
   BackButtonInterceptor.add(myInterceptor);
  }
   @override
 void initState() {
  super.initState();
  _searchControl.addListener(_onTextChanged);
 }

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

   if (_listener == null) {
    _listener = () {
      ricerca();
    };
   _searchControl.addListener(_listener);
 }
}

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

 Future<void> ricerca() async{
   if(_searchControl.text!=null){
   print("\n Sono in ricerca");
   foods = await Articolo.caricamento(null,_searchControl.text);
   foods = foods.where((item) => item.getCodArt().startsWith(_searchControl.text)).toList();
  
   //foods=foods.where((item) => item.getCodart().contains(_searchControl.text));
   print("\n foods: "+foods.length.toString());
   }
 }

  void _onTextChanged() {
    ricerca();

  }

  //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,
                        onChanged: (text) {
                         print("\n testo:"+ _searchControl.text);
    _onTextChanged();
  },
                      ),
                    ),
                  ),
                  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.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;
}

【问题讨论】:

  • 怎么样?............
  • @yes 在文本文件中

标签: flutter dart


【解决方案1】:

我认为你没有调用 setState。除非您调用此方法或使用某种状态管理,否则页面不会重建。 试试这个:

替换

   foods = foods
        .where((item) => item.getCodArt().startsWith(_searchControl.text))
        .toList();

setState(() {
    foods = foods
        .where((item) => item.getCodArt().startsWith(_searchControl.text))
        .toList();
  });

但是,我认为您不应该将其储存在食物中,因为它会在以后发生变化并变得无用。也许声明另一个变量来存储在您的搜索结果中。

【讨论】:

    猜你喜欢
    • 2020-05-03
    • 1970-01-01
    • 2020-12-28
    • 2011-09-11
    • 2023-01-19
    • 2022-07-07
    • 2023-03-26
    • 2021-05-30
    • 1970-01-01
    相关资源
    最近更新 更多