Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 如何从搜索结果导航到新页面_Flutter_Search_Navigation_Delegates - Fatal编程技术网

Flutter 如何从搜索结果导航到新页面

Flutter 如何从搜索结果导航到新页面,flutter,search,navigation,delegates,Flutter,Search,Navigation,Delegates,我正在尝试查找有关搜索导航的信息,但找不到任何合适的教程,说明如何在搜索后导航到特定页面。我希望有人能解释我是如何做到这一点的 搜索“谷歌”后,我想按下它,并通过导航重定向到一个新页面 import 'package:flutter/material.dart'; class SearchPage extends StatefulWidget { @override _SearchPageState createState() => _SearchPageState(); }

我正在尝试查找有关搜索导航的信息,但找不到任何合适的教程,说明如何在搜索后导航到特定页面。我希望有人能解释我是如何做到这一点的

搜索“谷歌”后,我想按下它,并通过导航重定向到一个新页面

import 'package:flutter/material.dart';

class SearchPage extends StatefulWidget {
  @override
  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  Widget appBarTitle = Text(
    "Search",
    style: TextStyle(color: Colors.white),
  );
  Icon actionIcon = Icon(
    Icons.search,
    color: Colors.white,
  );
  final key = GlobalKey<ScaffoldState>();
  final TextEditingController _searchQuery = TextEditingController();

  List<String> _list;

  bool _isSearching;

  String _searchText = "";

  _SearchPageState() {
    _searchQuery.addListener(() {
      if (_searchQuery.text.isEmpty) {
        setState(() {
          _isSearching = false;
          _searchText = "";
        });
      } else {
        setState(() {
          _isSearching = true;
          _searchText = _searchQuery.text;
        });
      }
    });
  }

  @override
  void initState() {
    super.initState();
    _isSearching = false;
    initData();
  }

  void initData() {
    _list = List();
    _list.add("google");
    _list.add("IOS");
    _list.add("Android");
    _list.add("Linux");
    _list.add("MacOS");
    _list.add("Windows");
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      key: key,
      appBar: buildBar(context),
      body: new ListView(
        padding: new EdgeInsets.symmetric(vertical: 8.0),
        children: _isSearching ? _buildSearchList() : _buildList(),
      ),
    );
  }

  List<ChildItem> _buildList() {
    return _list.map((contact) => new ChildItem(contact)).toList();
  }

  List<ChildItem> _buildSearchList() {
    if (_searchText.isEmpty) {
      return _list.map((contact) => new ChildItem(contact))
          .toList();
    }
    else {
      List<String> _searchList = List();
      for (int i = 0; i < _list.length; i++) {
        String  name = _list.elementAt(i);
        if (name.toLowerCase().contains(_searchText.toLowerCase())) {
          _searchList.add(name);
        }
      }
      return _searchList.map((contact) => new ChildItem(contact))
          .toList();
    }
  }

  Widget buildBar(BuildContext context) {
    return new AppBar(
        centerTitle: true,
        title: appBarTitle,
        actions: <Widget>[
          new IconButton(icon: actionIcon, onPressed: () {
            setState(() {
              if (this.actionIcon.icon == Icons.search) {
                this.actionIcon = new Icon(Icons.close, color: Colors.white,);
                this.appBarTitle = new TextField(
                  controller: _searchQuery,
                  style: new TextStyle(
                    color: Colors.white,

                  ),
                  decoration: new InputDecoration(
                      prefixIcon: new Icon(Icons.search, color: Colors.white),
                      hintText: "search...",
                      hintStyle: new TextStyle(color: Colors.white)
                  ),
                );
                _handleSearchStart();
              }
              else {
                _handleSearchEnd();
              }
            });
          },),
        ]
    );
  }

  void _handleSearchStart() {
    setState(() {
      _isSearching = true;
    });
  }

  void _handleSearchEnd() {
    setState(() {
      this.actionIcon = new Icon(Icons.search, color: Colors.white,);
      this.appBarTitle =
      new Text("search", style: new TextStyle(color: Colors.white),);
      _isSearching = false;
      _searchQuery.clear();
    });
  }

}

class ChildItem extends StatelessWidget {
  final String name;
  ChildItem(this.name);
  @override
  Widget build(BuildContext context) {
    return new ListTile(title: new Text(this.name));
  }

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Search Example"),
        actions: [
          IconButton(
              icon: Icon(Icons.search),
              onPressed: () {
                showSearch(context: context, delegate: SearchItem());
              }),
        ],
      ),
    );
  }
}

final List<String> myList = [
  "google",
  "IOS",
  "Android",
  "Linux",
  "MacOS",
  "Windows"
];

class SearchItem extends SearchDelegate<String> {
  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
          icon: Icon(Icons.clear),
          onPressed: () {
            query = "";
          })
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
        icon: AnimatedIcon(
          icon: AnimatedIcons.menu_arrow,
          progress: transitionAnimation,
        ),
        onPressed: () {
          close(context, null);
        });
  }

  @override
  Widget buildResults(BuildContext context) {}

  @override
  Widget buildSuggestions(BuildContext context) {
    final suggestionsList = query.isEmpty
        ? myList
        : myList
            .where((p) => p.toLowerCase().contains(query.toLowerCase()))
            .toList();

    return ListView.builder(
      itemBuilder: (context, index) => ListTile(
        onTap: () {
          close(context, suggestionsList[index]);
          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => DetailScreen(myList
                      .indexWhere((item) => item == suggestionsList[index]))));
        },
        title: Text(suggestionsList[index]),
      ),
      itemCount: suggestionsList.length,
    );
  }
}

class DetailScreen extends StatelessWidget {
  final int index;

  DetailScreen(this.index);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("${myList[index]}"),),
        body: Center(
          child: Text(
            "${myList[index]}",style: TextStyle(fontSize: 22),
      ),
    ));
  }
}
导入“包装:颤振/材料.省道”;
类SearchPage扩展StatefulWidget{
@凌驾
_SearchPageState createState()=>\u SearchPageState();
}
类_SearchPageState扩展状态{
Widget appBarTitle=文本(
“搜索”,
样式:TextStyle(颜色:Colors.white),
);
图标动作图标=图标(
Icons.search,
颜色:颜色,白色,
);
final key=GlobalKey();
final TextEditingController_searchQuery=TextEditingController();
列表(u List),;
布尔乌正在研究;
字符串_searchText=“”;
_SearchPageState(){
_searchQuery.addListener((){
if(_searchQuery.text.isEmpty){
设置状态(){
_isSearching=假;
_searchText=“”;
});
}否则{
设置状态(){
_isSearching=true;
_searchText=\u searchQuery.text;
});
}
});
}
@凌驾
void initState(){
super.initState();
_isSearching=假;
initData();
}
void initData(){
_list=list();
_添加(“谷歌”);
_列表。添加(“IOS”);
_添加(“安卓”);
_添加(“Linux”);
_列表。添加(“MacOS”);
_列表。添加(“窗口”);
}
@凌驾
小部件构建(构建上下文){
归还新脚手架(
钥匙:钥匙,
appBar:buildBar(上下文),
正文:新列表视图(
填充:新边集。对称(垂直:8.0),
子项:_isSearching?_buildSearchList():_buildList(),
),
);
}
列表_buildList(){
return _list.map((contact)=>newchilditem(contact)).toList();
}
列表_buildSearchList(){
if(_searchText.isEmpty){
return _list.map((contact)=>newchildItem(contact))
.toList();
}
否则{
List _searchList=List();
对于(int i=0;i<\u list.length;i++){
字符串名称=_list.elementAt(i);
if(name.toLowerCase()包含(_searchText.toLowerCase()){
_搜索列表。添加(名称);
}
}
return _searchList.map((contact)=>newchildItem(contact))
.toList();
}
}
小部件构建栏(构建上下文){
返回新的AppBar(
标题:对,
标题:appBarTitle,
行动:[
新图标按钮(图标:操作图标,按下按钮:(){
设置状态(){
if(this.actionIcon.icon==Icons.search){
this.actionIcon=新图标(Icons.close,颜色:Colors.white,);
this.appBarTitle=新文本字段(
控制器:\u searchQuery,
样式:新文本样式(
颜色:颜色,白色,
),
装饰:新的输入装饰(
前缀图标:新图标(Icons.search,颜色:Colors.white),
hintText:“搜索…”,
hintStyle:新文本样式(颜色:Colors.white)
),
);
_handleSearchStart();
}
否则{
_handleSearchEnd();
}
});
},),
]
);
}
void_handleSearchStart(){
设置状态(){
_isSearching=true;
});
}
void_handleSearchEnd(){
设置状态(){
this.actionIcon=新图标(Icons.search,颜色:Colors.white,);
这个是appBarTitle=
新文本(“搜索”,样式:新文本样式(颜色:Colors.white),);
_isSearching=假;
_searchQuery.clear();
});
}
}
类ChildItem扩展了无状态小部件{
最后的字符串名;
ChildItem(此名称);
@凌驾
小部件构建(构建上下文){
返回新的ListTile(标题:新文本(this.name));
}
}

您也可以使用
SearchDelegate
执行此操作

构建建议
下进行查询和导航

@override
  Widget buildSuggestions(BuildContext context) {
    final suggestionsList = query.isEmpty
        ? myList
        : myList
            .where((p) => p.toLowerCase().contains(query.toLowerCase()))
            .toList();

    return ListView.builder(
      itemBuilder: (context, index) => ListTile(
        onTap: () {
          close(context, suggestionsList[index]);
          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => DetailScreen(myList
                      .indexWhere((item) => item == suggestionsList[index]))));
        },
        title: Text(suggestionsList[index]),
      ),
      itemCount: suggestionsList.length,
    );
  }
正在将列表的
索引
与suggestionList
索引
配对:

MaterialPageRoute(
              builder: (context) => DetailScreen(myList
                  .indexWhere((item) => item == suggestionsList[index])))
下面是所有导航代码

import 'package:flutter/material.dart';

class SearchPage extends StatefulWidget {
  @override
  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  Widget appBarTitle = Text(
    "Search",
    style: TextStyle(color: Colors.white),
  );
  Icon actionIcon = Icon(
    Icons.search,
    color: Colors.white,
  );
  final key = GlobalKey<ScaffoldState>();
  final TextEditingController _searchQuery = TextEditingController();

  List<String> _list;

  bool _isSearching;

  String _searchText = "";

  _SearchPageState() {
    _searchQuery.addListener(() {
      if (_searchQuery.text.isEmpty) {
        setState(() {
          _isSearching = false;
          _searchText = "";
        });
      } else {
        setState(() {
          _isSearching = true;
          _searchText = _searchQuery.text;
        });
      }
    });
  }

  @override
  void initState() {
    super.initState();
    _isSearching = false;
    initData();
  }

  void initData() {
    _list = List();
    _list.add("google");
    _list.add("IOS");
    _list.add("Android");
    _list.add("Linux");
    _list.add("MacOS");
    _list.add("Windows");
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      key: key,
      appBar: buildBar(context),
      body: new ListView(
        padding: new EdgeInsets.symmetric(vertical: 8.0),
        children: _isSearching ? _buildSearchList() : _buildList(),
      ),
    );
  }

  List<ChildItem> _buildList() {
    return _list.map((contact) => new ChildItem(contact)).toList();
  }

  List<ChildItem> _buildSearchList() {
    if (_searchText.isEmpty) {
      return _list.map((contact) => new ChildItem(contact))
          .toList();
    }
    else {
      List<String> _searchList = List();
      for (int i = 0; i < _list.length; i++) {
        String  name = _list.elementAt(i);
        if (name.toLowerCase().contains(_searchText.toLowerCase())) {
          _searchList.add(name);
        }
      }
      return _searchList.map((contact) => new ChildItem(contact))
          .toList();
    }
  }

  Widget buildBar(BuildContext context) {
    return new AppBar(
        centerTitle: true,
        title: appBarTitle,
        actions: <Widget>[
          new IconButton(icon: actionIcon, onPressed: () {
            setState(() {
              if (this.actionIcon.icon == Icons.search) {
                this.actionIcon = new Icon(Icons.close, color: Colors.white,);
                this.appBarTitle = new TextField(
                  controller: _searchQuery,
                  style: new TextStyle(
                    color: Colors.white,

                  ),
                  decoration: new InputDecoration(
                      prefixIcon: new Icon(Icons.search, color: Colors.white),
                      hintText: "search...",
                      hintStyle: new TextStyle(color: Colors.white)
                  ),
                );
                _handleSearchStart();
              }
              else {
                _handleSearchEnd();
              }
            });
          },),
        ]
    );
  }

  void _handleSearchStart() {
    setState(() {
      _isSearching = true;
    });
  }

  void _handleSearchEnd() {
    setState(() {
      this.actionIcon = new Icon(Icons.search, color: Colors.white,);
      this.appBarTitle =
      new Text("search", style: new TextStyle(color: Colors.white),);
      _isSearching = false;
      _searchQuery.clear();
    });
  }

}

class ChildItem extends StatelessWidget {
  final String name;
  ChildItem(this.name);
  @override
  Widget build(BuildContext context) {
    return new ListTile(title: new Text(this.name));
  }

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Search Example"),
        actions: [
          IconButton(
              icon: Icon(Icons.search),
              onPressed: () {
                showSearch(context: context, delegate: SearchItem());
              }),
        ],
      ),
    );
  }
}

final List<String> myList = [
  "google",
  "IOS",
  "Android",
  "Linux",
  "MacOS",
  "Windows"
];

class SearchItem extends SearchDelegate<String> {
  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
          icon: Icon(Icons.clear),
          onPressed: () {
            query = "";
          })
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
        icon: AnimatedIcon(
          icon: AnimatedIcons.menu_arrow,
          progress: transitionAnimation,
        ),
        onPressed: () {
          close(context, null);
        });
  }

  @override
  Widget buildResults(BuildContext context) {}

  @override
  Widget buildSuggestions(BuildContext context) {
    final suggestionsList = query.isEmpty
        ? myList
        : myList
            .where((p) => p.toLowerCase().contains(query.toLowerCase()))
            .toList();

    return ListView.builder(
      itemBuilder: (context, index) => ListTile(
        onTap: () {
          close(context, suggestionsList[index]);
          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => DetailScreen(myList
                      .indexWhere((item) => item == suggestionsList[index]))));
        },
        title: Text(suggestionsList[index]),
      ),
      itemCount: suggestionsList.length,
    );
  }
}

class DetailScreen extends StatelessWidget {
  final int index;

  DetailScreen(this.index);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("${myList[index]}"),),
        body: Center(
          child: Text(
            "${myList[index]}",style: TextStyle(fontSize: 22),
      ),
    ));
  }
}
导入“包装:颤振/材料.省道”;
void main()=>runApp(MyApp());
类MyApp扩展了无状态小部件{
@凌驾
小部件构建(构建上下文){
返回材料PP(
debugShowCheckedModeBanner:false,
主页:主页(),
);
}
}
类主页扩展了无状态小部件{
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
标题:文本(“搜索示例”),
行动:[
图标按钮(
图标:图标(Icons.search),
已按下:(){
showSearch(上下文:context,委托:SearchItem());
}),
],
),
);
}
}
最终列表myList=[
“谷歌”,
“IOS”,
“安卓”,
“Linux”,
“MacOS”,
“窗口”
];
类SearchItem扩展了SearchDelegate{
@凌驾
列出buildActions(BuildContext上下文){
返回[
图标按钮(
图标:图标(图标。清除),
已按下:(){
query=“”;
})
];
}
@凌驾
小部件buildLeading(BuildContext上下文){
返回图标按钮(
图标:动画指令(
图标:animateDictions.menu\u箭头,
进展:过渡化,
),
已按下:(){
关闭(上下文,空);
});
}
@凌驾
小部件buildResults(BuildContext上下文){}
@凌驾
小部件构建建议(构建上下文){
final suggestionsList=query.isEmpty
?myList
:myList
.where((p)=>p.toLowerCase().contains(query.toLowerCase()))
.toList();
返回ListView.builder(
itemBuilder:(上下文,索引)=>ListTile(
onTap:(){
关闭(上下文、建议列表[索引]);