如何将数据从api加载到searchDelegate函数中?

时间:2020-07-30 03:35:01

标签: json http flutter

我正在尝试将newsapi的数据用于searchDelegate。为了搜索并显示结果,我不知道如何加载数据-有任何建议吗?

这是我的代码=>

Main.dart

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        theme: ThemeData(scaffoldBackgroundColor: Color(0xFFf5f5f2)),
        home: MyAppBar());
  }
}

class MyAppBar extends StatefulWidget {
  @override
  _MyAppBarState createState() => _MyAppBarState();
}

class _MyAppBarState extends State<MyAppBar> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFFf5f5f2),
      appBar: AppBar(
        backgroundColor: Color(0xFFf5f5f2),
        title: Text(
          'Search Bar',
          style: GoogleFonts.permanentMarker(fontSize: 30, color: Colors.black38),
        ),
        actions: <Widget>[
          IconButton(icon: Icon(Icons.search), onPressed: () {
            showSearch(context: context, delegate: SearchArticle());
          })
        ],
      ),
    );
  }
}

searchFunction

如何加载数据以便在buildSuggestion和buildResults函数中使用它们。

class SearchArticle 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, color: Colors.grey), onPressed: (){
        close(context, null);
      });
    }
  
    @override
    Widget buildResults(BuildContext context) {
      throw UnimplementedError();
    }
  
    @override
    Widget buildSuggestions(BuildContext context) {
      throw UnimplementedError(); 
  }
  
}

models.dart

class Article {
  final String urlToImage;
  final String publishedAt;
  final String author;
  final String title;
  final String content;

  Article({this.urlToImage, this.publishedAt, this.author, this.title, this.content});
}

webService.dart

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'models.dart';

class News{
  List<Article> news = [];

  Future<void> fetchArticle() async {
    final url = 
    'http://newsapi.org/v2/everything?q=apple&from=2020-07-29&to=2020-07-29&sortBy=popularity&apiKey={Your api key}';

    var response = await http.get(url);
    var data = jsonDecode(response.body);

    if(data == 200){
      data['articles'].forEach((e){

        if(e['urlToImage'] != null) {
          Article article = Article(
            urlToImage : e['urlToImage'],
            publishedAt: e['publishedAt'],
            author: e['author'],
            title: e['title'],
            content: e['content']
          );
          news.add(article);
      }
      
      });
    }
  }
}

1 个答案:

答案 0 :(得分:0)

将fetchArticle的返回类型更改为Future<List<Article>>

尝试使用FutureBuilder,使用future属性加载文章,如下所示:

Widget buildResults(BuildContext context) {
  return FutureBuilder(
    future: News.fetchArticle,
    builder: (context, AsyncSnapshot<List<Article>> snapshot) {
      if(snapshot != null)
        return Text("No articles found!");
      else {
        return ListView.builder(
          itemCount: snapshot.data.length,
          builder: (context, pos) {
            ....
          }
        );
      }
    }
  );
}