Skip to content

Instantly share code, notes, and snippets.

@guites
Created February 3, 2022 00:54
Show Gist options
  • Save guites/3d799bf707e9eaf17808382a0fecce04 to your computer and use it in GitHub Desktop.
Save guites/3d799bf707e9eaf17808382a0fecce04 to your computer and use it in GitHub Desktop.
Código para a barra de busca em Flutter
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.barra_de_buscas">
<!-- Required to fetch data from the internet. -->
<uses-permission android:name="android.permission.INTERNET" />
<application
android:label="last_test_searchbar"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
import 'dart:convert';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(const MyApp());
}
class BreedsList {
final List<Breed> breeds;
BreedsList({
required this.breeds,
});
factory BreedsList.fromJson(List<MapEntry<String, dynamic>> parsedJson) {
List<Breed> breeds = <Breed>[];
breeds = parsedJson.map((i) => Breed.fromJson(i)).toList();
return BreedsList(breeds: breeds);
}
}
class Breed {
final String name;
final List<dynamic> subBreeds;
const Breed({
required this.name,
required this.subBreeds,
});
factory Breed.fromJson(json) {
return Breed(
name: json.key,
subBreeds: json.value,
);
}
}
Future<BreedsList> fetchBreeds() async {
final response =
await http.get(Uri.parse('https://dog.ceo/api/breeds/list/all'));
if (response.statusCode == 200) {
var responseObject =
jsonDecode(response.body)['message'].entries.toList();
return BreedsList.fromJson(responseObject);
}
// Joga uma exceção caso o status não seja http 200
throw Exception('Erro ao carregar listagem de raças.');
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Searchbar Http',
theme: ThemeData(primarySwatch: Colors.grey),
home: const SearchPage(title: 'Flutter search bar!'),
);
}
}
class SearchPage extends StatefulWidget {
const SearchPage({Key? key, required this.title}) : super(key: key);
final String title;
@override
_SearchPageState createState() => _SearchPageState();
}
class _SearchPageState extends State<SearchPage> {
late Future<BreedsList> futureBreeds;
/// Define o ícone inicial usado na barra de busca
IconData _searchIcon = Icons.search;
/// Define o título inicial da página
Widget _appBarTitle = const Text('Listagem de raças');
/// Essa variável vai guardar o valor digitado na barra de busca
String _searchText = "";
/// Esta variável vai guardar os valores filtrados, que devemos mostrar ao usuário na listagem
List<Breed> _filteredBreeds = [];
@override
void initState() {
super.initState();
futureBreeds = fetchBreeds();
}
List<Breed> _applySearchFilter(List<Breed> breeds) {
List<Breed> _filtered = [];
for (var i = 0; i < breeds.length; i++) {
if (breeds[i].name.contains(_searchText.toLowerCase())) {
_filtered.add(breeds[i]);
}
}
return _filtered;
}
void _searchPressed() {
setState(() {
if (_searchIcon == Icons.search) {
_searchIcon = Icons.close;
/// Altera o título, inicialmente um widget de texto, para um TextField
_appBarTitle = TextField(
onChanged: (text) {
setState(() {
_searchText = text;
});
},
decoration: const InputDecoration(
prefixIcon: Icon(Icons.search),
hintText: 'Busque por raças...'),
);
} else {
_searchIcon = Icons.search;
/// Altera o título novamente para um widget de texto
_appBarTitle = const Text('Listagem de raças');
_searchText = "";
}
});
}
Widget _buildListOfBreeds(List<Breed> breedList) {
return ListView.builder(
padding: const EdgeInsets.all(16.0),
itemCount: breedList.length,
itemBuilder: (context, i) {
return Column(children: [
Text(breedList[i].name,
style:
const TextStyle(fontWeight: FontWeight.bold, fontSize: 18.0)),
const Divider()
]);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: _appBarTitle,
actions: <Widget>[
IconButton(
onPressed: _searchPressed,
icon: Icon(_searchIcon),
)
],
),
body: FutureBuilder<BreedsList>(
future: futureBreeds,
builder: (context, snapshot) {
if (snapshot.hasData) {
final _filteredList =
_applySearchFilter(snapshot.data!.breeds);
if (_filteredList.isEmpty) {
return const Center(
child: Text("Nenhuma raça encontrada!"));
}
return _buildListOfBreeds(_filteredList);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return const Center(
child: CircularProgressIndicator(),
);
}),
);
}
}
name: last_test_searchbar
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.15.1 <3.0.0"
# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
flutter:
sdk: flutter
http: ^0.13.4
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
dev_dependencies:
flutter_test:
sdk: flutter
# The "flutter_lints" package below contains a set of recommended lints to
# encourage good coding practices. The lint set provided by the package is
# activated in the `analysis_options.yaml` file located at the root of your
# package. See that file for information about deactivating specific lint
# rules and activating additional ones.
flutter_lints: ^1.0.0
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment