【问题标题】:How to load data from api into searchDelegate function?如何将 api 中的数据加载到 searchDelegate 函数中?
【发布时间】:2020-11-19 18:20:24
【问题描述】:

我正在尝试将 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());
          })
        ],
      ),
    );
  }
}

搜索功能

我如何加载数据以便在 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);
      }
      
      });
    }
  }
}

【问题讨论】:

    标签: json http flutter


    【解决方案1】:

    将fetchArticle的返回类型改为Future&lt;List&lt;Article&gt;&gt;

    尝试使用 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) {
                ....
              }
            );
          }
        }
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-23
      • 2020-04-06
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 2017-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多