如何从搜索栏中保存搜索到的项目并如何在flutter中显示来自共享首选项的已保存列表

时间:2020-01-22 08:50:59

标签: flutter sharedpreferences

我试图将搜索到的项目从搜索栏保存到sharedpreference,并且想要在其他页面中显示搜索到的列表的列表,但无法实现。以下是我的代码如何从共享首选项中保存和检索它。

我已经更新了我的代码,请仔细检查。

更新 我有查询,将其传递给网址并直接获取列表

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Ayurwikilist> ayurwikilist = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text('Ayurwiki'),
        actions: <Widget>[
          new IconButton(
            icon: new Icon(Icons.search),
            onPressed: () {
              showSearch(
                  context: context,
                  delegate: CustomSearchDelegate(ayurwikilist));
            },
          ),
        ],
      ),
      body: _body(),
    );
  }

class CustomSearchDelegate extends SearchDelegate {
  List<Ayurwikilist> ayurwikilist = [];
  CustomSearchDelegate(this.ayurwikilist);

  Future<Ayurwikilist> fetchPost() async {
    final response = await http.get(
        'https://www.example.org/api.php?action=query&list=search&srsearch=$query&utf8=&format=json');
    print(
        'https://www.example.org/api.php?action=query&list=search&srsearch=$query&utf8=&format=json');
    return Ayurwikilist.fromJson(json.decode(response.body));
  }

  @override
  ThemeData appBarTheme(BuildContext context) {
    assert(context != null);
    final ThemeData theme = Theme.of(context);
    assert(theme != null);
    return theme;
  }

 @override
 List<Widget> buildActions(BuildContext context) {
   return [
     IconButton(
       icon: Icon(Icons.clear),
       onPressed: () async{
         query = '';
         SharedPreferences prefs = await SharedPreferences.getInstance();
         prefs.setString('name', "$query");
         print(query);
       },
     ),
   ];
 }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      icon: Icon(Icons.arrow_back),
      onPressed: () {
        close(context, null);
      },
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    return Container();
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    return FutureBuilder<Ayurwikilist>(
      future: fetchPost(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.hasData) {
          print(snapshot.data.toString());
          return ListView.builder(
              itemCount: snapshot.data.query.search.length,
              itemBuilder: (BuildContext context, int index) {
                var title = snapshot.data.query.search[index].title;
                return GestureDetector(
                  onTap: () {
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => Detailpage(
                            snapshot.data.query.search[index].title,
                            // 'images/ayurwiki.png'
                          ),
                        ));
                  },
                  child: ListTile(
                    title: Text(title),
                  ),
                );
              });
        } else {
          return Center(
            child: Text(
              'Search in ayurwiki',
              style: TextStyle(color: Colors.grey, fontSize: 18),
            ),
          );
        }
      },
    );
  }
}
class _HistoryState extends State<History> {

var myName;

 getCredential() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var query = prefs.getString('query');
    setState(() {
      myName = query;
    });
    print('item : $query');
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title:Text('Rcently viewed item'),
      ),
      body: Container(
          decoration: new BoxDecoration(color: Colors.white),
          child: myName == null ? Text('No items') : Text('$myName'),
      ),
    );
  }
}

更新

Future<Ayurwikilist> fetchPost() async {
    final response = await http.get(
        'https://www.example.org/api.php?action=query&list=search&srsearch=$query&utf8=&format=json');
    print(
        'https://www.example.org/api.php?action=query&list=search&srsearch=$query&utf8=&format=json');
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setStringList('name', query as List);
    return Ayurwikilist.fromJson(json.decode(response.body));
  }
getCredential() async {
   SharedPreferences prefs = await SharedPreferences.getInstance();
   var name = prefs.getStringList('name');
   setState(() {
     myName = name;
   });
   print('item : $name');
 }

1 个答案:

答案 0 :(得分:1)

您应该在initState中调用getCredential()函数

class _HistoryState extends State<History> {

 var myName;

 initState(){
    super.initState();
    getCredential();
 }

 getCredential() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var query = prefs.getString('query');
    setState(() {
      myName = query;
    });
    print('item : $query');
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title:Text('Rcently viewed item'),
      ),
      body: Container(
          decoration: new BoxDecoration(color: Colors.white),
          child: myName == null ? Text('No items') : Text('$myName'),
      ),
    );
  }
}

更新:

Future<Ayurwikilist> fetchPost() async {
    query = 'something you need';
    final response = await http.get(
        'https://www.example.org/api.php?action=query&list=search&srsearch=$query&utf8=&format=json');
    print(
        'https://www.example.org/api.php?action=query&list=search&srsearch=$query&utf8=&format=json');
    prefs.setString('name', query);
    return Ayurwikilist.fromJson(json.decode(response.body));
  }