父页面,传值给子组件,子组件把数据传递给二级页面
父页面
final List _datas; // 通过接口请求到的数据...
...// 父页面中的子组件:SearchCell
body: Container(child:SearchCell(datas: _datas,);
)
子组件:SearchCell
class SearchCell extends StatelessWidget {final List? datas;const SearchCell({this.datas});
}// 触发某次点击事件,把datas传递过去
onTap: (){Navigator.of(context).push(// 把数据传递给搜索页MaterialPageRoute(builder: (BuildContext context)=> SearchPage(datas: datas,)));
},
搜索页
class SearchPage extends StatefulWidget {final List? datas;const SearchPage({this.datas});@overrideState<SearchPage> createState() => SearchPageState();
}
class SearchPageState extends State<SearchPage> {final List _modals = [];// 根据搜索的内容去检索上个页面传来的datasvoid _searchData(String text) {// 每次搜索先清空_modals.clear();if(text.length>0){for(int i = 0; i < widget.datas.length; i ++){String name = widget.datas[i].name;// contains 是否包含if(name.contains(text)){_modals.add(widget.datas[i]);}}}}........children: [SearchBar(onChanged: (String texts){_searchData(text);},),]
}// 搜索页内的小部件,头部的搜索框,
class SearchBar extends StatefulWidget {// 定义onChanged的回调方法final ValueChanged<String>? onChanged;const SearchBar({this.onChanged});@overrideState<SearchBar> createState() => SearchBarState();
}
class SearchBarState extends State<SearchBar> {// 监听输入框的变化void _onChange(String value){if(widget.onChanged != null){widget.onChanged!(value);}}
}
输入框变化后,检索datas的内容: