'How can I make a search bar in a my ListView
How can I make a search bar in this list view that have list of data I tried searching on YouTube but I always get errors and none of them worked
// ignore_for_file: use_key_in_widget_constructors, avoid_print, avoid_unnecessary_containers, curly_braces_in_flow_control_structures, prefer_const_constructors, non_constant_identifier_names, unnecessary_new, avoid_function_literals_in_foreach_calls, unused_import
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:myapp2/Service_Request/SR.dart';
import 'package:myapp2/main.dart';
import 'package:myapp2/Service_Request/second.dart';
import '../Classes/demandes.dart';
import 'SR_details.dart';
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DataFromAPI(),
);
}
}
class DataFromAPI extends StatefulWidget {
@override
_DataFromAPIState createState() => _DataFromAPIState();
}
List<Attributes> MyAllData = [];
class _DataFromAPIState extends State<DataFromAPI> {
@override
void initState() {
super.initState();
}
Future<List<Sr>> loadData() async {
try {
var response = await http.get(Uri.parse(
'http://192.168.1.30:9080/maxrest/rest/mbo/sr/?_lid=azizl&_lpwd=max12345m&_format=json'));
if (response.statusCode == 200) {
final jsonBody = json.decode(response.body);
Demandes data = Demandes.fromJson(jsonBody);
final srAttributes = data.srMboSet.sr;
return srAttributes;
}
} catch (e) {
throw Exception(e.toString());
}
throw Exception("");
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: new Scaffold(
appBar: AppBar(
title: Text('Liste des Demandes'),
leading: IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () => Navigator.push(
context, MaterialPageRoute(builder: (context) => SR()))),
),
body: FutureBuilder<List<Sr>?>(
future: loadData(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return CircularProgressIndicator();
} else {
return new ListView.builder(
itemCount: snapshot.data?.length,
itemBuilder: ((_, index) {
return new ListTile(
title: new Card(
margin: new EdgeInsets.symmetric(
vertical: 2.0, horizontal: 8.0),
elevation: 10,
child: new ListTile(
title: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(padding: new EdgeInsets.all(2.0)),
new Text(
'Ticket ID : ${snapshot.data![index].attributes.ticketid.content}'),
new Text(
'status : ${snapshot.data![index].attributes.status.content}'),
new Text(
'description : ${snapshot.data![index].attributes.description?.content}'),
new Text(
'Reported by : ${snapshot.data![index].attributes.reportedby.content}'),
new Text(
'Location : ${snapshot.data![index].attributes.location?.content}'),
new Text(
'Asset num : ${snapshot.data![index].attributes.assetnum?.content}'),
new Text(
'Asset site id : ${snapshot.data![index].attributes.assetsiteid?.content}'),
new Text(
'Reoprt date : ${snapshot.data![index].attributes.statusdate.content}'),
new Text(
'LONG DESCRIPTION : ${snapshot.data![index].attributes.DESCRIPTION_LONGDESCRIPTION?.content}'),
new Text(
'ticket u id : ${snapshot.data![index].attributes.ticketuid.content}'),
],
),
trailing: Icon(Icons.arrow_forward_ios_rounded),
),
),
onTap: () {
Navigator.of(context)
.push(
new MaterialPageRoute(
builder: (BuildContext context) =>
new SrDetailsScreen(
sr: snapshot.data![index]),
),
)
.then((data) {});
});
}));
}
},
),
),
);
}
}
Solution 1:[1]
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
// Remove the debug banner
debugShowCheckedModeBanner: false,
title: 'Kindacode.com',
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
// This holds a list of fiction users
// You can use data fetched from a database or a server as well
final List<Map<String, dynamic>> _allUsers = [
{"id": 1, "name": "Andy", "age": 29},
{"id": 2, "name": "Aragon", "age": 40},
{"id": 3, "name": "Bob", "age": 5},
{"id": 4, "name": "Barbara", "age": 35},
{"id": 5, "name": "Candy", "age": 21},
{"id": 6, "name": "Colin", "age": 55},
{"id": 7, "name": "Audra", "age": 30},
{"id": 8, "name": "Banana", "age": 14},
{"id": 9, "name": "Caversky", "age": 100},
{"id": 10, "name": "Becky", "age": 32},
];
// This list holds the data for the list view
List<Map<String, dynamic>> _foundUsers = [];
@override
initState() {
// at the beginning, all users are shown
_foundUsers = _allUsers;
super.initState();
}
// This function is called whenever the text field changes
void _runFilter(String enteredKeyword) {
List<Map<String, 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: AppBar(
title: const Text('Anand'),
),
body: Padding(
padding: const EdgeInsets.all(10),
child: Column(
children: [
const SizedBox(
height: 20,
),
TextField(
onChanged: (value) => _runFilter(value),
decoration: const InputDecoration(
labelText: 'Search', suffixIcon: Icon(Icons.search)),
),
const SizedBox(
height: 20,
),
Expanded(
child: _foundUsers.isNotEmpty
? ListView.builder(
itemCount: _foundUsers.length,
itemBuilder: (context, index) => Card(
key: ValueKey(_foundUsers[index]["id"]),
color: Colors.amberAccent,
elevation: 4,
margin: const EdgeInsets.symmetric(vertical: 10),
child: ListTile(
leading: Text(
_foundUsers[index]["id"].toString(),
style: const TextStyle(fontSize: 24),
),
title: Text(_foundUsers[index]['name']),
subtitle: Text(
'${_foundUsers[index]["age"].toString()} years old'),
),
),
)
: const Text(
'No results found',
style: TextStyle(fontSize: 24),
),
),
],
),
),
);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Dharman |