首页 > 解决方案 > 如何将 api 数据从 WordPress 博客页面导入到 flutter 中的 searchDelegate 函数中?

问题描述

我创建了飞镖页面,但我不知道如何将数据设置到 searchDelegate 函数中

接口代码

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

class ApiNewsPage {
  String baseUrl = "https://www.assofacile.it/wp-json/wp/v2/posts?_embed";

  Future<List> getNewsArticles() async {
    try {
      var response = await http.get(Uri.parse(baseUrl));
      //print(response);
      if (response.statusCode == 200) {
        return jsonDecode(response.body);
      } else {
        return Future.error("Server Error");
      }
      // ignore: non_constant_identifier_names
    } catch (SocketException) {
      return Future.error("Error Fetching Data");
    }
  }
}

标签: wordpressflutterapisearchbaruisearchbardelegate

解决方案


文章页面

导入“包:颤振/material.dart”;导入“包:share/share.dart”;导入'包:flutter_widget_from_html_core/flutter_widget_from_html_core.dart';

class ArticlePage extends StatelessWidget {
 

  final data;
  const ArticlePage({Key? key, required this.data}) : super(key: key);
  // Share article
  final String _content = "Condividi l'app con i tuoi contatti";
  void _shareContent() {Share.share(_content);}


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: CustomScrollView(
        slivers: <Widget>[
          SliverAppBar(
            leading: Builder(
              builder: (BuildContext context) {
                return GestureDetector(
                  child: Center(
                    child: Container(
                      color: Colors.white70.withOpacity(0),
                      child: Container(
                        height: 30,
                        width: 30,
                        decoration: const BoxDecoration(
                          image: DecorationImage(
                            image: AssetImage(
                              'assets/images/previous.png',
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                  onTap: () {
                    Navigator.of(context).pop();
                  },
                );
              },
            ),
            flexibleSpace: FlexibleSpaceBar(
              centerTitle: true,
              background: Image.network(data["_embedded"]["wp:featuredmedia"][0]["source_url"], fit: BoxFit.cover,),
            ),
            floating: true,
            expandedHeight: 320,
            actions: <Widget>[
              IconButton(
                onPressed: _shareContent,
                color: Colors.blue.shade900,
                iconSize: 35,
                icon: const SizedBox(
                  child: Image(
                    image: AssetImage('assets/images/share-icon.png',), fit: BoxFit.cover,
                  ),
                  height: 30, width: 30,
                ),
              ),
            ],
          ),
          SliverList(
            delegate: SliverChildListDelegate([
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    const SizedBox(height: 20,),
                    // Title container
                    Container(
                      padding: const EdgeInsets.all(16),
                      child: Text(data['title']['rendered']
                            .toString()
                            .replaceAll("<p>", "")
                            .replaceAll("</p>", ""),
                        style: const TextStyle(
                          fontWeight: FontWeight.w600,
                          fontSize: 20,
                          fontFamily: "Raleway",
                        ),
                      ),
                    ),
                    const SizedBox(height: 0),
                    Container(
                      padding: const EdgeInsets.all(16),
                      child: HtmlWidget(
                        data['content']['rendered'],
                      ),
                    ),
                    const SizedBox(height: 20),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}




class SearchBar extends SearchDelegate{@override String get searchFieldLabel => "Cerca articolo";
  @override
  ThemeData appBarTheme(BuildContext context) {
    return Theme.of(context).copyWith(
      appBarTheme: const AppBarTheme(color: Color(0xFF0D47A1),),
      accentColor: Colors.white,
      textSelectionTheme: const TextSelectionThemeData(cursorColor: Color(0xFFFFFFFF), 
      ),
      textTheme: const TextTheme(
        headline1: TextStyle(color: Colors.black,),
        headline2: TextStyle(color: Colors.black,),
        bodyText1: TextStyle(color: Colors.black,),
      ),
      inputDecorationTheme: const InputDecorationTheme(
        isDense: true,// this will remove the default content padding
        alignLabelWithHint: true,
      ),
    );
  }
 
  List suggestions = [ 'Documentazione', 'Registro nazionale', 'Attività sportive', 'Agevolazioni fiscali', 'Terzo Settore', 'Pro Loco',];
  List data = [];
  //
  @overrideList<Widget> buildActions(BuildContext context) {return[IconButton(icon: const Icon(Icons.clear), onPressed: () {query = '';},),];}
  //
  @override
  Widget buildLeading(BuildContext context) {return IconButton(icon: const Icon(Icons.arrow_back_ios), onPressed: () {close(context, query);},);}
  //
  @override
  Widget buildResults(BuildContext context) {
    List result = suggestions.where((element) => element.toLowerCase().contains(query.toLowerCase())).toList();
    return query.isEmpty ? const Center(child: Text("Nessun  articolo trovato"),) : ListView.builder(itemCount: result.length, itemBuilder: (context, index) {return ListTile(title: Text(result[index],),);});}
  @override
  Widget buildSuggestions(BuildContext context) {
    List searchedList = suggestions.isEmpty ? data : suggestions.where((element) => element.toLowerCase().contains(query.toLowerCase())).toList();
    return ListView.builder(itemCount: searchedList.length, itemBuilder: (context, index) {return ListTile(title: Text(searchedList[index],),);});
  }
}

推荐阅读