Advertisement
danielbrito1987

data_search

Mar 12th, 2019
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 2.10 KB | None | 0 0
  1. import 'dart:convert';
  2.  
  3. import 'package:flutter/material.dart';
  4. import 'package:http/http.dart' as http;
  5.  
  6. class DataSearch extends SearchDelegate<String> {
  7.   @override
  8.   List<Widget> buildActions(BuildContext context) {
  9.     return [
  10.       IconButton(
  11.         icon: Icon(Icons.clear),
  12.         onPressed: (){
  13.           query = "";
  14.         },
  15.       )
  16.     ];
  17.   }
  18.  
  19.   @override
  20.   Widget buildLeading(BuildContext context) {
  21.     return IconButton(
  22.       icon: AnimatedIcon(
  23.         icon: AnimatedIcons.menu_arrow,
  24.         progress: transitionAnimation,
  25.       ),
  26.       onPressed: (){
  27.         close(context, null);
  28.       },
  29.     );
  30.   }
  31.  
  32.   @override
  33.   Widget buildResults(BuildContext context) {
  34.     Future.delayed(Duration.zero).then((_) => close(context, query));
  35.  
  36.     return Container();
  37.   }
  38.  
  39.   @override
  40.   Widget buildSuggestions(BuildContext context) {
  41.     if(query.isEmpty)
  42.       return Container();
  43.     else {
  44.       return FutureBuilder<List>(
  45.         future: suggestions(query),
  46.         builder: (context, snaphshot) {
  47.           if(!snaphshot.hasData) {
  48.             return Center(
  49.               child: CircularProgressIndicator(),
  50.             );
  51.           } else {
  52.             return ListView.builder(
  53.               itemBuilder: (context, index) {
  54.                 return ListTile(
  55.                   title: Text(snaphshot.data[index]),
  56.                   leading: Icon(Icons.play_arrow),
  57.                   onTap: (){
  58.                     close(context, snaphshot.data[index]);
  59.                   },
  60.                 );
  61.               },
  62.               itemCount: snaphshot.data.length,
  63.             );
  64.           }
  65.         },
  66.       );
  67.     }
  68.   }
  69.  
  70.   Future<List> suggestions(String search) async {
  71.     http.Response response = await http.get(
  72.       "http://suggestqueries.google.com/complete/search?hl=en&ds=yt&client=youtube&hjson=t&cp=1&q=$search&format=5&alt=json"
  73.     );
  74.  
  75.     if(response.statusCode == 200) {
  76.       return json.decode(response.body)[1].map((v) {
  77.         return v[0];
  78.       }).toList();
  79.     } else {
  80.       throw Exception("Erro ao carregar sugestões");
  81.     }
  82.   }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement