Created
May 5, 2021 19:17
-
-
Save SergioEric/de482c3a4319b8b7036b90857abff594 to your computer and use it in GitHub Desktop.
Filtro en local de una palabra
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
debugShowCheckedModeBanner: false, | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: MyHomePage(title: 'Flutter Futere and filter'), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
MyHomePage({Key key, this.title}) : super(key: key); | |
final String title; | |
@override | |
_MyHomePageState createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
// donde seran guardados los resultados que vengan de la api | |
final List<String> allResult = []; | |
//un valueNotifer para construir los resultados filtrados sin necesidad | |
//de hacer setState y volver a ejecutar el [build] | |
final filterResults = ValueNotifier<List<String>>([]); | |
// se supone la mayoria de aplicaciones ejecutan el fetching de lo | |
// que se quiera traer del servidor en el metodo initState | |
Future<List<String>> getSomething() async { | |
// esta parte simula la peticion a tu servidor | |
// la cual te devuelve la lista de los productos | |
await Future.delayed(const Duration(seconds: 2)); | |
// pasados los 2 segundos se devuelve los resultados | |
// aqui asigno ese resultado a la lsita de todos los resultados | |
allResult.addAll([ | |
"uno", | |
"dos", | |
"tres", | |
"cuatro", | |
"cinco", | |
"seis", | |
"uno y dos", | |
"dos y uno", | |
"cuatro y seis", | |
]); | |
// inicialmente los productos filtrados tienen los mismos valores | |
filterResults.value = allResult; | |
// retornamos los resultados de este future | |
return Future.value(allResult); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text(widget.title), | |
), | |
body: Column( | |
children: [ | |
Text("Busqueda"), | |
Container( | |
padding: const EdgeInsets.symmetric(horizontal: 20), | |
height: 50, | |
child: TextFormField( | |
decoration: InputDecoration(hintText: 'filtra por nombre'), | |
onChanged: (String value) { | |
// se filtra en el valueNotifier | |
// y cada que cambie, se actualizará | |
// la lista dentro del futureBuilder | |
filterResults.value = allResult | |
.where( | |
(state) => state.toLowerCase().contains( | |
value.toLowerCase(), | |
), | |
) | |
.toList(); | |
}, | |
), | |
), | |
const SizedBox(height: 100), | |
Expanded( | |
child: FutureBuilder( | |
// lo ideal es que el metodo que traiga los datos no se vuelva | |
// a ejecutar cuando se hace el build del widget | |
// por ello es mejor que este se llame en el initState | |
future: getSomething(), | |
builder: (_, AsyncSnapshot<List<String>> snapshot) { | |
if (snapshot.hasData) { | |
final List<String> resultados = snapshot.data; | |
if (resultados.isEmpty) return const Text("Sin resultados"); | |
return ValueListenableBuilder( | |
valueListenable: filterResults, | |
builder: (_, filtrados, __) { | |
return ListView.builder( | |
itemCount: filtrados.length, | |
itemBuilder: (_, index) { | |
return ListTile( | |
//ignora esta propiedad :) | |
visualDensity: const VisualDensity(vertical: -2), | |
title: Text(filtrados[index]), | |
); | |
}, | |
); | |
}, | |
); | |
} | |
// mientras se traen los datos del servidor | |
return const Center(child: CircularProgressIndicator()); | |
}, | |
), | |
), | |
], | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment