Issue
Hi guys I have a list of categories and what I'm trying to do is search for a category by it's name and display the matched category inside the same view :
The problem is now I can't type a text inside that searchfield and when I remove the function onChanged everything goes back to normal and I can type text again
this is my code :
class _HomeScreen00State extends State<HomeScreen00> {
Category category = new Category();
List myIds = [];
List myServiceNames = [];
List myImagesUrl = [];
bool isLogin;
List<Category> _searchResult = [];
TextEditingController controllerSearchField = new TextEditingController();
List<Category> _categoryDetails = [];
onSearchTextChanged(String text) async {
_searchResult.clear();
if (text.isEmpty) {
setState(() {});
return;
}
_categoryDetails.forEach((_categoryDetail) {
if (_categoryDetail.name.contains(text) )
_searchResult.add(_categoryDetail);
});
setState(() {});
}
@override
void initState() {
// Calling API using Bloc
super.initState();
fetchAlbum();
}
@override
Widget build(BuildContext context) {
TextEditingController controllerSearchField = new TextEditingController();
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(83),
child: SafeArea(
child: Container(
color: AppColors.white,
height: 83,
child: Form(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
height: 65,
width: 350,
child: TextFormField(
controller: controllerSearchField,
onChanged:(value) => onSearchTextChanged(value),
decoration: InputDecoration(
hintStyle: TextStyle(
color: AppColors.white,
),
prefixIcon: Icon(
Icons.search,
color: AppColors.white,
),
hintText: 'Pesquisar por serviço...',
fillColor: AppColors.grey2,
filled: true,
border: OutlineInputBorder(
borderSide: BorderSide.none,
borderRadius: BorderRadius.circular(08),
),
suffixIcon: IconButton(
icon: Icon(Icons.cancel_outlined),
color: AppColors.white,
onPressed: () {
controllerSearchField.clear();
onSearchTextChanged('');
},
)),
),
),
],
),
),
),
),
),
body: Stack(
children: [
Container(
alignment: Alignment.topCenter,
child: test() as Widget,
),
Container(
alignment: Alignment(-0.9, -0.35),
child: Text(
'Serviços',
style: TextStyle(
color: AppColors.blackCupons,
fontSize: 15,
fontWeight: FontWeight.bold),
),
),
_searchResult.length != 0 || controllerSearchField.text.isNotEmpty
?Positioned.fill(
top: 180,
child: GridView.builder(
padding: const EdgeInsets.all(20.0),
physics: ScrollPhysics(),
shrinkWrap: true,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2, mainAxisSpacing: 12, crossAxisSpacing: 12),
itemCount: _searchResult.length,
itemBuilder: (BuildContext context, int index) {
final Widget image = Material(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(4)),
clipBehavior: Clip.antiAlias,
child: Image.network(
ApiConstants.BASE_URL + _searchResult[index].imageUrl,
fit: BoxFit.cover,
),
);
final Widget name = FittedBox(
fit: BoxFit.scaleDown,
alignment: AlignmentDirectional.centerStart,
child: Text(_searchResult[index].name),
);
return GestureDetector(
onTap: () async {
print("card id : " + myIds[index].toString());
isLogin = await FlutterSession().get("isLogin");
if (isLogin == false || isLogin == null) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => LoginPage(),
),
);
} else {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProfissionaisList(),
),
);
}
},
child: GridTile(
footer: Material(
color: Colors.transparent,
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.vertical(bottom: Radius.circular(4)),
),
clipBehavior: Clip.antiAlias,
child: GridTileBar(
backgroundColor: AppColors.grey3,
title: name,
),
),
child: image,
),
);
},
),
):
Positioned.fill(
top: 180,
child: GridView.builder(
padding: const EdgeInsets.all(20.0),
physics: ScrollPhysics(),
shrinkWrap: true,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2, mainAxisSpacing: 12, crossAxisSpacing: 12),
itemCount: myImagesUrl.length,
itemBuilder: (BuildContext context, int index) {
final Widget image = Material(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(4)),
clipBehavior: Clip.antiAlias,
child: Image.network(
ApiConstants.BASE_URL + myImagesUrl[index],
fit: BoxFit.cover,
),
);
final Widget name = FittedBox(
fit: BoxFit.scaleDown,
alignment: AlignmentDirectional.centerStart,
child: Text(myServiceNames[index]),
);
return GestureDetector(
onTap: () async {
print("card id : " + myIds[index].toString());
isLogin = await FlutterSession().get("isLogin");
if (isLogin == false || isLogin == null) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => LoginPage(),
),
);
} else {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProfissionaisList(),
),
);
}
},
child: GridTile(
footer: Material(
color: Colors.transparent,
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.vertical(bottom: Radius.circular(4)),
),
clipBehavior: Clip.antiAlias,
child: GridTileBar(
backgroundColor: AppColors.grey3,
title: name,
),
),
child: image,
),
);
},
),
),
],
),
);
}
}
I removed the API consumption code and some session verification if you need full code I can update it any help would be appreciated
Solution
This is how I fixed this issue with a new solution full code : (you can remove the undefined variables it's for display purpose and the code should be working fine )
class HomeScreen00 extends StatefulWidget {
@override
_HomeScreen00State createState() => _HomeScreen00State();
}
class _HomeScreen00State extends State<HomeScreen00> {
List myIds = [];
List myServiceNames = [];
List myImagesUrl = [];
bool isLogin;
TextEditingController searchFieldController = new TextEditingController();
// This holds a list of fiction users
// You can use data fetched from a database or a server as well
List _allUsers = [];
// This list holds the data for the list view
List<dynamic> _foundUsers = [];
@override
initState() {
// at the beginning, all users are shown
super.initState();
verifLogin();
fetchAlbum();
}
// This function is called whenever the text field changes
void _runFilter(String enteredKeyword) {
List<dynamic> results = [];
if (enteredKeyword.isEmpty) {
// if the search field is empty or only contains white-space, we'll display all users
results = _allUsers;
} else {
results = _allUsers
.where((user) =>
user["name"].toLowerCase().contains(enteredKeyword.toLowerCase()))
.toList();
// we use the toLowerCase() method to make it case-insensitive
}
// Refresh the UI
setState(() {
_foundUsers = results;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(83),
child: SafeArea(
child: Container(
color: AppColors.white,
height: 83,
child: Form(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
height: 65,
width: 350,
child: TextField(
controller: searchFieldController,
onChanged: (value) => _runFilter(value),
decoration: InputDecoration(
hintStyle: TextStyle(
color: AppColors.white,
),
prefixIcon: Icon(
Icons.search,
color: AppColors.white,
),
hintText: 'Pesquisar por serviço...',
fillColor: AppColors.grey2,
filled: true,
border: OutlineInputBorder(
borderSide: BorderSide.none,
borderRadius: BorderRadius.circular(08),
),
suffixIcon: IconButton(
icon: Icon(Icons.cancel_outlined),
color: AppColors.white,
onPressed: () {
searchFieldController.clear();
},
)),
),
),
],
),
),
),
),
),
body: Padding(
padding: const EdgeInsets.all(10),
child: Stack(
children: [
Container(
alignment: Alignment.topCenter,
child: test() as Widget,
),
Container(
alignment: Alignment(-0.9, -0.35),
child: Text(
'Serviços',
style: TextStyle(
color: AppColors.blackCupons,
fontSize: 15,
fontWeight: FontWeight.bold),
),
),
Positioned.fill(
top: 180,
child: GridView.builder(
padding: const EdgeInsets.all(20.0),
physics: ScrollPhysics(),
shrinkWrap: true,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
mainAxisSpacing: 12,
crossAxisSpacing: 12),
itemCount: _foundUsers.length,
itemBuilder: (BuildContext context, int index) {
final Widget image = Material(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(4)),
clipBehavior: Clip.antiAlias,
child: Image.network(
ApiConstants.BASE_URL + _foundUsers[index]["imageUrl"],
fit: BoxFit.cover,
),
);
final Widget name = FittedBox(
fit: BoxFit.scaleDown,
alignment: AlignmentDirectional.centerStart,
child: Text(_foundUsers[index]['name']),
);
return GestureDetector(
onTap: () async {
print("card id : " + myIds[index].toString());
isLogin = await FlutterSession().get("isLogin");
if (isLogin == false || isLogin == null) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => LoginPage(),
),
);
} else {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProfissionaisList(),
),
);
}
},
child: GridTile(
footer: Material(
color: Colors.transparent,
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.vertical(bottom: Radius.circular(4)),
),
clipBehavior: Clip.antiAlias,
child: GridTileBar(
backgroundColor: AppColors.grey3,
title: name,
),
),
child: image,
),
);
},
),
),
],
),
),
);
}
Future<List<Category>> fetchAlbum() async {
final response = await http
.get(Uri.parse(ApiConstants.BASE_URL + ApiConstants.CATEGORIES));
if (response.statusCode == 200) {
final list = json.decode(response.body) as List<dynamic>;
_allUsers = list;
print("all users inside fn");
print(_allUsers);
setState(() {
_foundUsers = _allUsers;
//2 ways to do this add all elements to a list or add each element in a list
// how to access the index of the lists inside the widget otherwise you can
//access it this way example : myIds[index]
list.forEach((element) {
myIds.add(element['id']);
myServiceNames.add(element['name']);
myImagesUrl.add(element['imageUrl']);
});
});
print("---Category info---");
print("myIDS: " + myIds.toString());
print("my Services : " + myServiceNames.toString());
print("my image url: " + myImagesUrl.toString());
return list.map((e) => Category.fromJson(e)).toList();
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
}
Answered By - Selim
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.