I needed to insert a TextField to search/filter records, but I don't know what's going on.
When I click on the "Cães" option of the BottomNavigationBar, on main.dart,
I only get a CircularProgressIndicator and the data does show up.
Have any of you experienced this problem?
Does anyone know why my Listview doesn't show up?
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:ssk_final/addeditpage.dart';
//import 'package:flutter_localizations/flutter_localizations.dart';
List<dynamic> list = [];
class CaesPage extends StatefulWidget {
// CaesPage({Key key}) : super(key: key);
#override
_CaesPageState createState() => _CaesPageState();
Widget build(BuildContext context) {
return Container(
child: Center(
child: Text("Cadastro de Cães"),
),
);
}
}
class _CaesPageState extends State<CaesPage> {
String searchString = "";
Future<List<Caes>> caes;
Future getData() async {
var url = 'http://.../api2.php?opcao=read';
var response = await http.get(Uri.parse(url));
return json.decode(response.body);
}
/*
Future _showMyDialog(id, nome) async {
return showDialog<void>(
context: context,
barrierDismissible: false, // user must tap button
builder: (BuildContext context) {
return AlertDialog(
title: Text('Exclusão'),
content: SingleChildScrollView(
child: Column(
children: <Widget>[
Text('Confirma a exclusão de ' + nome + '?'),
],
),
),
actions: <Widget>[
TextButton(
child: Text('Confirma'),
onPressed: () {
setState(() {
var url = 'http://.../api.php?opt=delete';
http.post(Uri.parse(url), body: {
'id': id,
});
});
Navigator.pop(context, true);
},
),
TextButton(
child: Text('Cancelar'),
onPressed: () {
Navigator.pop(context);
},
),
],
);
},
);
}
*/
#override
void initState() {
super.initState();
caes = fetchCaes();
}
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
backgroundColor: Color.fromRGBO(1, 87, 155, 1),
focusColor: Colors.blue,
foregroundColor: Colors.white,
hoverColor: Colors.green,
splashColor: Colors.tealAccent,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AddEditPage(),
),
);
debugPrint('Clicked FloatingActionButton Button');
},
),
body: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Divider(),
//SizedBox(height: 10),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 15.0),
child: TextField(
onChanged: (value) {
setState(() {
searchString = value.toLowerCase();
});
},
decoration: const InputDecoration(
//contentPadding: EdgeInsets.symmetric(vertical: 10),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blue, width: 1.0),
borderRadius: BorderRadius.all(Radius.circular(25.0))),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blue, width: 1.0),
borderRadius: BorderRadius.all(Radius.circular(25.0)),
),
labelText: 'Pesquisa',
suffixIcon: Icon(Icons.search))),
),
SizedBox(height: 10),
Expanded(
child: FutureBuilder<List<Caes>>(
builder: (context, snapshot) {
if (snapshot.hasData) {
return Center(
child: ListView.separated(
padding: const EdgeInsets.all(8),
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return snapshot.data[index].nome
.toLowerCase()
.contains(searchString)
? Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new InkWell(
onTap: () {
print(index);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AddEditPage(
caes: snapshot.data,
index: index,
),
),
);
},
child: new Container(
child: Column(
children: [
Text(
(snapshot.data[index].nome),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold),
),
Text(
('${snapshot.data[index].microchip}'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13,
),
),
Text(
('${snapshot.data[index].pedigree}'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13,
),
),
Text(
(snapshot
.data[index].data_nascimento),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13,
),
),
Text(
(snapshot.data[index].sexo),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13,
),
),
Text(
(snapshot.data[index].castrado),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13,
),
),
],
),
),
),
])
: Container();
},
separatorBuilder: (BuildContext context, int index) {
return snapshot.data[index].nome
.toLowerCase()
.contains(searchString)
? Divider()
: Container();
},
),
);
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
}
return Center(
child: CircularProgressIndicator(),
);
},
// future: list,
),
),
],
),
);
}
}
class Caes {
final int id;
final String nome;
final int microchip;
final int pedigree;
final String data_nascimento;
final String castrado;
final String sexo;
Caes({
this.id,
this.nome,
this.microchip,
this.pedigree,
this.data_nascimento,
this.castrado,
this.sexo,
});
factory Caes.fromJson(Map<String, dynamic> json) {
return Caes(
id: json['id'],
nome: json['nome'],
microchip: json['microchip'],
pedigree: json['pedigree'],
data_nascimento: json['data_nascimento'],
castrado: json['castrado'],
sexo: json['sexo'],
);
}
}
class Titulos {
Titulos({this.data, this.titulo, this.exposicao});
// non-nullable - assuming the score field is always present
final String data;
final String titulo;
final String exposicao;
factory Titulos.fromJson(Map<String, dynamic> json) {
final data = json['data'] as String;
final titulo = json['titulo'] as String;
final exposicao = json['exposicao'] as String;
return Titulos(data: data, titulo: titulo, exposicao: exposicao);
}
Map<String, dynamic> toJson() {
return {
'data': data,
'titulo': titulo,
'exposicao': exposicao,
};
}
}
Future<List<Caes>> fetchCaes() async {
final response = await http.get(Uri.parse('http://.../api.php?opt=read'));
if (response.statusCode == 200) {
var caesJson = jsonDecode(response.body) as List;
return caesJson.map((caes) => Caes.fromJson(caes)).toList();
} else {
throw Exception('Failed to load Caes');
}
}
Screen
I cant really provide an answer in your list view cause it needs more files to run for me. However I can provide you a nice way to search in a list for items and update it with a text field. You can copy and run the code in the main of a test project to see how it is working.
import 'dart:async';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final StreamController<List<String>> _exercisesStreamController =
StreamController<List<String>>();
late Stream<List<String>> _exercisesStream;
final List<String> _exercises = [
"Running",
"Swimming",
"Football",
"Basketball",
"Volleyball",
"Karate",
"Ski",
"Snowboard",
"Baseball",
"Running1",
"Swimming1",
"Football1",
"Basketball1",
"Volleyball1",
"Karate1",
"Ski1",
"Snowboard1",
"Baseball1",
"Running2",
"Swimming2",
"Football2",
"Basketball2",
"Volleyball2",
"Karate2",
"Ski2",
"Snowboard2",
"Baseball2",
"Running3",
"Swimming3",
"Football3",
"Basketball3",
"Volleyball3",
"Karate3",
"Ski3",
"Snowboard3",
"Baseball3",
];
#override
void initState() {
super.initState();
_exercisesStreamController.sink.add(_exercises);
_exercisesStream = _exercisesStreamController.stream.asBroadcastStream();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(),
body: Padding(
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
child: Column(
children: [
TextFormField(
maxLines: 1,
style: TextStyle(color: Colors.white),
onChanged: (String value) async {
List<String> temp = List.from(_exercises);
temp.removeWhere((element) =>
!element.toLowerCase().contains(value.toLowerCase()));
_exercisesStreamController.sink.add(temp);
},
decoration: InputDecoration(
prefixIcon: Icon(
Icons.search,
color: Colors.white,
),
border: OutlineInputBorder(
borderSide: BorderSide.none,
borderRadius: BorderRadius.circular(15.0),
),
contentPadding: EdgeInsets.only(left: 15),
filled: true,
fillColor: Colors.blueGrey,
hintText: "search",
hintStyle: TextStyle(
color: Colors.white,
),
),
),
_listViewWidget()
],
),
),
);
}
Widget _listViewWidget() {
return Expanded(
child: StreamBuilder<List<String>>(
initialData: [],
stream: _exercisesStream,
builder: (context, snapshot) {
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
return Container(
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
color: Colors.blueGrey,
borderRadius: BorderRadius.all(
Radius.circular(15),
),
),
padding: EdgeInsets.all(15),
margin: EdgeInsets.symmetric(vertical: 10),
child: Center(
child: Text(
snapshot.data![index],
style: TextStyle(color: Colors.white),
),
),
);
});
},
),
);
}
}
If you need further instructions i am happy to help.
Related
am building a flutter app and am am working with a data from a API i got the list and evreything i did a search bar that works properly by typing either the number of the ticket or the description but am trying to add a new filter , a checkbox that filters the data i have 2 problems
1: when i press on a checkbox and type confirm it works and it shows but the checkbox dosent stay checked
2: how can i implement it so it filter the data from the api directly
and thank you
// 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, avoid_types_as_parameter_names, unused_label, unused_element, file_names, library_private_types_in_public_api, unnecessary_string_interpolations
import 'dart:convert';
import 'dart:io';
import 'package:az/Actifs.dart';
import 'package:az/SR_Details.dart';
import 'package:az/main.dart';
import 'package:badges/badges.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import 'class/sr.dart';
import 'package:dropdown_search/dropdown_search.dart';
class DataFromAPI extends StatefulWidget {
#override
_DataFromAPIState createState() => _DataFromAPIState();
}
List<Sr> _MyAllData=[];
List<Sr> _SrForDsiplay=[];
Map<String, Color> map={
"QUEUED":Color.fromARGB(255, 255, 136, 0),
"CLOSED":Colors.grey,
"Rejected":Colors.red,
"INPROG":Colors.green,
"PENDING":Colors.blue,
"RESOLVED":Colors.green,
"NEW":Colors.blue,
};
Map<String, String> map1={
"1":"Urgent",
"2":"High",
"3":"Medium",
"4":"Low",
};
/*Map<String, Color> map3={
"Urgent":Colors.red,
"High":Color.fromARGB(255, 255, 139, 131),
"Medium":Colors.blue,
"Low":Colors.green,
"null":Colors.grey,
};*/
class Multiselect extends StatefulWidget {
final List<String> items;
const Multiselect({Key? key, required this.items}) : super(key: key);
#override
State<Multiselect> createState() => _MultiselectState();
}
class _MultiselectState extends State<Multiselect> {
final List<String> _selectedItems=[];
void _itemChange(String itemValue, bool isSelected) {
setState(() {
if (isSelected) {
_selectedItems.add(itemValue);
} else {
_selectedItems.remove(itemValue);
}
});
}
// this function is called when the Cancel button is pressed
void _cancel() {
Navigator.pop(context);
}
// this function is called when the Submit button is tapped
void _submit() {
Navigator.pop(context, _selectedItems);
}
#override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Select Topics'),
content: SingleChildScrollView(
child: ListBody(
children: widget.items
.map((item) => CheckboxListTile(
value: _selectedItems.contains(item),
title: Text(item),
controlAffinity: ListTileControlAffinity.leading,
onChanged: (isChecked) => _itemChange(item, isChecked!),
))
.toList(),
),
),
actions: [
TextButton(
onPressed: _cancel,
child: const Text('Cancel'),
),
ElevatedButton(
onPressed: _submit,
child: const Text('Submit'),
),
],
);
}
}
class _DataFromAPIState extends State<DataFromAPI> {
List<String> _selectedItems=[];
String title_string = "Liste des SR :";
void _ShowMultiSelect() async{
final List<String> items=[
'QUEUED',
'CLOSED',
'Rejected',
'INPROG',
'PENDING',
'RESOLVED',
'NEW',
];
final List<String>? results =await showDialog(
context: context,
builder: (BuildContext context) {
return Multiselect(items: items);
},
);
if(results !=null){
setState(() {
_selectedItems=results;
});
}
}
#override
void initState() {
loadData().then((value) {
_MyAllData.clear();
setState(() {
_MyAllData.addAll(value);
_SrForDsiplay=_MyAllData;
});
});
super.initState();
}
Future<List<Sr>> loadData() async {
try {
var response = await http.get(Uri.parse(
'http:MXSR/?_lid=&_lpwd=&_format=json'));
if (response.statusCode == 200) {
final jsonBody = json.decode(response.body);
Demandes data = Demandes.fromJson(jsonBody);
final srAttributes = data.queryMxsrResponse.mxsrSet.sr;
title_string='Liste des SR : ${srAttributes.length.toString()}';
return srAttributes;
}
} catch (e) {
throw Exception(e.toString());
}
throw Exception("");
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner:false,
home: new Scaffold(resizeToAvoidBottomInset: false ,
appBar: AppBar(
title: Text(title_string),
leading: IconButton(
icon: Icon(Icons.arrow_back), onPressed: () { Navigator.push(
context, MaterialPageRoute(builder: (context) => Home())); },
),
flexibleSpace: InkWell(onTap: () {
},),
),
body: FutureBuilder<List<Sr>?>(
future: loadData(),
builder: (context, snapshot) {
if (_MyAllData.isEmpty) {
return SizedBox(
height: MediaQuery.of(context).size.height / 1.3,
child: Center(
child: CircularProgressIndicator(),
),
);
} else { return
ListView(
children: <Widget>[Padding(
padding: const EdgeInsets.all(8.0),
child: Column(children:<Widget>[ElevatedButton(onPressed: _ShowMultiSelect,
child: const Text('Filter')),
const Divider(
height: 30,
),
Wrap(
children: _selectedItems
.map((e) => Chip(
label: Text(e),
))
.toList(),
),
Row(children:<Widget>[ Expanded(
child: TextField(
decoration:
InputDecoration( hintText: "Enter id or description"),
onChanged: (text) {
text=text.toLowerCase();
setState(() {
_SrForDsiplay =_MyAllData.where((srAttributes) {
var srDescription = srAttributes.attributes.description!.content.toString().toLowerCase();
var srID= srAttributes.attributes.ticketid.content.toString();
return srDescription.contains(text) || srID.contains(text);
}).toList();
title_string='Liste des SR : ${_SrForDsiplay.length.toString()}';
print(title_string);
}
);
},
)),])
],
),),
new ListView.builder(scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: _SrForDsiplay.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)),
Row(children :[
Container(
decoration: BoxDecoration(
border: Border.all(
color: Color.fromARGB(255, 255, 255, 255),
),
color: map['${_SrForDsiplay[index].attributes.status.content}'],
borderRadius: BorderRadius.all(Radius.circular(20)),
),
child:Text(' ${_SrForDsiplay[index].attributes.status.content} '),
),
Container(child: Text(' '),),
Container(
decoration: BoxDecoration(
border: Border.all(
color: Color.fromARGB(255, 255, 255, 255),
),
color:Colors.grey,
borderRadius: BorderRadius.all(Radius.circular(20)),
),
child:Text( map1['${_SrForDsiplay[index].attributes.reportedpriority?.content}'] ?? " null "),
),
],
),
SizedBox(
height: 8,
),
Row(children: <Widget>[
Expanded( child: Container(child: Text('${_SrForDsiplay[index].attributes.description?.content}',style: GoogleFonts.openSans(
textStyle: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600)),),),),
Expanded(child: Container(child:Text( ' ${_SrForDsiplay[index].attributes.ticketid.content}',style: GoogleFonts.openSans(
textStyle: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w400)),)))
],),
new Divider(
color: Color.fromARGB(255, 110, 109, 109),
),
Text(
'Reported : ${DateFormat.yMMMMEEEEd().format(DateTime.parse('${_SrForDsiplay[index].attributes.statusdate.content}' ))}' ,
style: GoogleFonts.openSans(
textStyle: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w400)),
),
new Text(
'Reported by : ${_SrForDsiplay[index].attributes.reportedby?.content}',style: GoogleFonts.openSans(
textStyle: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w400)),
),
Row(children: [new Image(image: AssetImage('assets/courroi.png'), width: 20),
Text(
'${_SrForDsiplay[index].relatedMbos?.asset[0].attributes.descriptionasset?.content}'),], ),
Row(children: [new Image(image: AssetImage('assets/emp.png'), width: 20),
Text(
'${_SrForDsiplay[index].attributes.assetsiteid?.content}'),], ) ,
Divider(
color: Color.fromARGB(255, 110, 109, 109),
),
Row(children:[
Expanded(child: Badge(
position: BadgePosition.topEnd(top: -8, end: 20),
badgeColor: Colors.grey,
badgeContent: Text('1'),
child :IconButton(icon :Icon(Icons.file_present_rounded), padding: const EdgeInsets.all(0),
onPressed: () {
},
),
)
),
Expanded(child: IconButton (
icon: Icon(Icons.file_copy),
onPressed: () { },
),),
Expanded(child: IconButton(onPressed:() {
}, icon: Icon(Icons.delete)) )
],)
],
),
trailing: Icon(Icons.arrow_forward_ios_rounded),
),
),
onTap: () {
Navigator.push(
context,MaterialPageRoute(builder: (context) =>SrDetailsScreen(sr: _SrForDsiplay[index])),
);
}
);
}
),
)
]
);
}
},
),
),
);
}
}
Hi guys i'm a begginer in flutter development , i am stuck in a problem,
problem is i want to redirect from selected (homepage.dart file) user in the list to chatroom where i can chat this user but i am not able to do, here is problem i'm facing: Anyone give me solution .
code:-
homepage.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:jobong/model/chatroom_model.dart';
import 'package:jobong/model/signup.dart';
import 'package:jobong/view/chatroom.dart';
class HomePage extends StatefulWidget {
final List<User>? users;
const HomePage({Key? key, this.users}) : super(key: key);
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final auth = FirebaseAuth.instance;
final systemColor =
const SystemUiOverlayStyle(statusBarColor: Colors.transparent);
final User? currentUser = FirebaseAuth.instance.currentUser;
final String uid = FirebaseAuth.instance.currentUser!.uid;
final searchController = TextEditingController();
String search = '';
#override
Widget build(BuildContext context) {
SystemChrome.setSystemUIOverlayStyle(systemColor);
return Scaffold(
backgroundColor: Colors.grey[300],
drawer: const Drawer(
child: DrawerPage(),
),
appBar: AppBar(
titleSpacing: 0,
backgroundColor: Colors.blue[900],
title: Text(
"ChatApp",
style: GoogleFonts.raleway(),
),
actions: [
IconButton(
onPressed: () async {
await FirebaseAuth.instance.signOut();
setState(() {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const SignUp()),
);
});
},
icon: const Icon(Icons.logout_outlined),
),
],
),
body: Column(
children: [
const SizedBox(height: 20),
Padding(
padding: const EdgeInsets.all(20.0),
child: TextFormField(
controller: searchController,
onChanged: (String value) {
search = value;
},
decoration: InputDecoration(
hintText: 'Search user',
prefixIcon: const Icon(Icons.search),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(20),
),
hintStyle: GoogleFonts.raleway(
fontSize: 16, fontWeight: FontWeight.normal),
),
),
),
ElevatedButton(
onPressed: () {
setState(() {});
},
child: Text(
"Search",
style: GoogleFonts.raleway(),
),
),
Expanded(
child: StreamBuilder<QuerySnapshot>(
stream:
FirebaseFirestore.instance.collection('Users')
.where('uid',isNotEqualTo: currentUser!.uid).snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
} else if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, index) {
DocumentSnapshot snap = snapshot.data!.docs[index];
final chatRoomModel = ChatRoomModel(
friendName: currentUser!.displayName.toString(),
friendUid: currentUser!.uid,
friendEmail: currentUser!.email.toString(),
);
final targetUserName = chatRoomModel.friendName;
final targetUserEmail = chatRoomModel.friendEmail ;
final targetUserUid = chatRoomModel.friendUid;
if (search.isEmpty) {
return ListTile(
title: Text(snap['name']),
subtitle: Text(snap['email']),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
ChatRoom(
friendName: snap['name'] ,
friendEmail: snap['email'],
friendUid: snap['uid'],
),
),
);
},
leading: Container(
height: 45,
width: 45,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
color: Colors.white),
child: const Center(
child: Icon(Icons.person),
),
),
);
}
if (snap['name'].toString().toLowerCase().startsWith(search.toLowerCase()) ||
snap['name'].toString().toUpperCase().startsWith(search.toUpperCase())) {
return ListTile(
title: Text(snap['name']),
subtitle: Text(snap['email']),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
ChatRoom(
friendName: snap['name'] ,
friendEmail: snap['email'],
friendUid: snap['uid'],
),
),
);
},
leading: Container(
height: 45,
width: 45,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
color: Colors.white),
child: const Center(
child: Icon(Icons.person),
),
),
);
}
return Container();
},
);
} else if (snapshot.hasError) {
return const Center(
child: Text("Something went wrong!"),
);
} else {
return Container();
}
},
),
),
],
),
);
}
}
//..............................User Details Fetch here ??..........................................
class DrawerPage extends StatefulWidget {
const DrawerPage({Key? key}) : super(key: key);
#override
State<DrawerPage> createState() => _DrawerPageState();
}
class _DrawerPageState extends State<DrawerPage> {
#override
void initState() {
super.initState();
getUserData();
}
String name = '';
String email = '';
String password = '';
final currentUser = FirebaseAuth.instance.currentUser;
Future<void> getUserData() async {
final user = await FirebaseFirestore.instance
.collection('Users')
.doc(currentUser!.uid)
.get();
setState(() {
name = user.data()!['name'];
email = user.data()!['email'];
password = user.data()!['password'];
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Name: $name',
style: GoogleFonts.raleway(
fontWeight: FontWeight.normal, fontSize: 16),
),
const SizedBox(height: 10),
Text(
'Email: $email',
style: GoogleFonts.raleway(
fontWeight: FontWeight.normal, fontSize: 16),
),
const SizedBox(height: 10),
Text(
'Password: $password',
style: GoogleFonts.raleway(
fontWeight: FontWeight.normal, fontSize: 16),
),
],
),
),
);
}
}
second chatroom.dart file =================================
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:jobong/model/chatroom_model.dart';
class ChatRoom extends StatefulWidget {
final ChatRoomModel friendName;
final ChatRoomModel friendUid;
final ChatRoomModel friendEmail;
const ChatRoom({
Key? key,
required this.friendName, required this.friendUid ,
required this.friendEmail
}) : super(key: key);
#override
State<ChatRoom> createState() => _ChatRoomState();
}
class _ChatRoomState extends State<ChatRoom> {
void showToast(String message) {
Fluttertoast.showToast(
msg: message,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0
);
}
final email = FirebaseAuth.instance.currentUser!.email;
void sendMessage() async {
try{
await FirebaseFirestore.instance.collection('chats')
.doc(uid).collection('messages').doc()
.set({
'sender':email,
'receiver':widget.friendUid,
'message':_message.text.trim(),
'time':FieldValue.serverTimestamp(),
});
}on FirebaseAuthException catch (e) {
showToast('${e.message}');
}
}
final bool isMe = false;
final _message = TextEditingController();
final uid = FirebaseAuth.instance.currentUser!.uid;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Column(
children: [
Text(
widget.friendName.toString(),
style: GoogleFonts.lato(),
),
Text(
widget.friendEmail.toString(),
style: GoogleFonts.lato(),
),
],
),
),
body: Column(
children: [
Expanded(
child: StreamBuilder(
stream: FirebaseFirestore.instance
.collection('chats')
.doc(uid)
.collection('messages')
.doc()
.snapshots(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
return const Center(
child: CircularProgressIndicator(color: Colors.blue),
);
} else {
return ListView.builder(
shrinkWrap: true,
reverse: true,
itemCount: snapshot.data!.doc.length,
itemBuilder: (BuildContext context, index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: isMe
? CrossAxisAlignment.end
: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.all(15),
decoration: BoxDecoration(
borderRadius: isMe
? BorderRadius.circular(15.0)
: BorderRadius.circular(15.0),
color: isMe
? Colors.green[500]
: Colors.red[500]),
child: Center(
child: Text(_message.toString(),
style: isMe
? GoogleFonts.lato(color: Colors.black)
: GoogleFonts.lato(
color: Colors.white)),
),
),
],
),
);
},
);
}
},
),
),
Padding(
padding: const EdgeInsets.only(left: 8.0, right: 8.0, bottom: 8.0),
child: Container(
height: 60,
width: double.infinity,
decoration: BoxDecoration(
borderRadius: const BorderRadius.only(
bottomLeft: Radius.circular(25),
bottomRight: Radius.circular(25),
topLeft: Radius.circular(10),
topRight: Radius.circular(10),
),
color: Colors.grey[900],
),
child: TextFormField(
controller: _message,
style: GoogleFonts.lato(color: Colors.white),
decoration: InputDecoration(
hintText: 'send a message ...',
hintStyle: GoogleFonts.lato(color: Colors.white),
border: InputBorder.none,
prefixIcon: const Icon(Icons.file_present_rounded,
color: Colors.white),
suffixIcon: GestureDetector(
onTap:sendMessage,
child: const Icon(Icons.near_me, color: Colors.white),
),
),
),
),
),
],
),
);
}
}
I have a list in this file called check_symptoms.dart which the list is called _chosenItems
i want it to pass it to another file which is a stateful widget
here's my code for Check_symptoms.dart
import 'package:diagnose_app/results.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:flutter/services.dart';
class SymptomsChecker extends StatefulWidget {
const SymptomsChecker({Key? key}) : super(key: key);
#override
State<SymptomsChecker> createState() => _SymptomsCheckerState();
}
class _SymptomsCheckerState extends State<SymptomsChecker> {
List _items = [];
List _itemsForDisplay = [];
List _chosenItems = [];
int maxheight = 0;
ScrollController _scrollController = ScrollController();
Future<void> readJson() async {
final String response =
await rootBundle.loadString('assets/data/Symptoms.json');
final data = await json.decode(response);
setState(() {
_items = data["Symptoms"];
_itemsForDisplay = _items;
});
}
#override
void initState() {
// TODO: implement initState
readJson();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color.fromARGB(255, 105, 120, 255),
body: Padding(
padding: const EdgeInsets.all(5),
child: Column(
children: [
// Display the data loaded from sample.json
// _ListChosenItem(23),
SizedBox(
height: 25,
),
_searchBar(),
Divider(
height: 1,
),
Expanded(
child: ListView.builder(
itemBuilder: (context, index) {
return _ListItem(index);
},
itemCount: _itemsForDisplay.length,
),
),
Divider(
height: 2,
),
Padding(
padding: const EdgeInsets.all(3.0),
child: LimitedBox(
maxHeight: 200,
child: Scrollbar(
controller: _scrollController,
child: SingleChildScrollView(
//scrollDirection: Axis.horizontal,
child: Wrap(
children: _chosenItems.map((item) {
//print(_chosenItems);
return chosenItems(item);
}).toList(),
),
),
),
),
),
Divider(
color: Colors.black,
height: 10,
thickness: 1,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: Container(
height: 50,
width: double.infinity,
child: ElevatedButton(
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
// sending chosenItems to results.dart
builder: (context) => Results(list: _chosenItems)));
},
child: Text(
"Find Results",
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500),
),
style: ElevatedButton.styleFrom(),
),
),
),
SizedBox(
height: 5,
),
],
),
),
);
}
Padding chosenItems(item) {
return Padding(
padding: const EdgeInsets.all(3.0),
child: Builder(builder: (context) {
return ElevatedButton.icon(
onPressed: () {
setState(() {
_itemsForDisplay.add(item);
//_items.add(item);
_chosenItems.remove(item);
});
},
style: ElevatedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
textStyle:
const TextStyle(fontSize: 15, fontWeight: FontWeight.w400)),
label: Text(item),
icon: Icon(
Icons.remove_circle,
color: Color.fromARGB(255, 255, 217, 216),
),
);
}),
);
}
_searchBar() {
return Padding(
padding: const EdgeInsets.all(8),
child: TextField(
decoration: InputDecoration(
border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
filled: true,
fillColor: Color.fromARGB(255, 244, 244, 244),
hintText: 'Search Symptoms'),
style: TextStyle(color: Color.fromARGB(255, 22, 25, 52)),
maxLines: 1,
onChanged: (text) {
text = text.toLowerCase();
setState(() {
_itemsForDisplay = _items.where((item) {
var itemEntity = item.toLowerCase();
return itemEntity.contains(text);
}).toList();
});
},
),
);
}
_ListItem(index) {
return Wrap(
children: [
ElevatedButton(
onPressed: () {
setState(() {
_chosenItems.add(_itemsForDisplay[index]);
_itemsForDisplay.removeAt((index));
//_items.removeAt((index));
});
},
style: ElevatedButton.styleFrom(
textStyle:
const TextStyle(fontSize: 18, fontWeight: FontWeight.w500)),
child: Text(_itemsForDisplay[index]),
),
],
);
}
_ListChosenItem(index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Wrap(
children: [
ElevatedButton(
onPressed: () {},
style: ElevatedButton.styleFrom(
textStyle: const TextStyle(fontSize: 20)),
child: Text(_chosenItems[index]),
),
],
),
);
}
}
here's the way I'm receiving the list in results.dart
import 'package:flutter/material.dart';
class Results extends StatefulWidget {
final List list;
const Results({required this.list});
#override
State<Results> createState() => _ResultsState(list);
}
class _ResultsState extends State<Results> {
#override
Widget build(BuildContext context) {
print(list);
return Scaffold();
}
}
this line of code of results.dart
State<Results> createState() => _ResultsState(list);
is says:
List list Type: List
package:diagnose_app/results.dart
Don't put any logic in createState.dartno_logic_in_create_state Too
many positional arguments: 0 expected, but 1 found. Try removing the
extra arguments.
Am I passing the list in a wrong way? thanks for helping in advance.
First of all, an instance of State can access the members of its parent StatefulWidget via the widget property.
So your particular problem can be solved simply by accessing widget.list, you don't need to pass the list explicitly to _ResultsState:
import 'package:flutter/material.dart';
class Results extends StatefulWidget {
final List list;
const Results({required this.list});
#override
State<Results> createState() => _ResultsState();
}
class _ResultsState extends State<Results> {
#override
Widget build(BuildContext context) {
print(widget.list);
return Scaffold();
}
}
But further, if you do want to explicitly pass a value to a class constructor, you'll need to add the field as a member to the class and define the constructor that takes that value.
I'm working on simple chat features in my app. I have used OTP login method to do this application. Firebase Authentication is working well in my application. I have already done the code for the simple chat app but I would like to display the user's phone number when they send chat. Example pic added below for better understanding about the need:
This is my code:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import '../forum/message.dart';
class ForumScreen extends StatefulWidget {
String email;
ForumScreen({required this.email});
#override
_ForumScreenState createState() => _ForumScreenState(email: email);
}
class _ForumScreenState extends State<ForumScreen> {
String email;
_ForumScreenState({required this.email});
final fs = FirebaseFirestore.instance;
final _auth = FirebaseAuth.instance.currentUser;
final TextEditingController message = new TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Farmer's Forum"),
centerTitle: true,
automaticallyImplyLeading: false,
),
body: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
height: MediaQuery.of(context).size.height * 0.73,
child: messages(
email: email,
),
),
Row(
children: [
Expanded(
child: TextFormField(
controller: message,
decoration: InputDecoration(
filled: true,
fillColor: Colors.lightGreen,
hintText: 'message',
enabled: true,
contentPadding: const EdgeInsets.only(
left: 14.0, bottom: 8.0, top: 8.0),
focusedBorder: OutlineInputBorder(
borderSide: new BorderSide(color: Colors.black),
borderRadius: new BorderRadius.circular(10),
),
enabledBorder: UnderlineInputBorder(
borderSide: new BorderSide(color: Colors.black),
borderRadius: new BorderRadius.circular(10),
),
),
validator: (value) {},
onSaved: (value) {
message.text = value!;
},
),
),
IconButton(
onPressed: () {
if (message.text.isNotEmpty) {
fs.collection('Messages').doc().set({
'message': message.text.trim(),
'time': DateTime.now(),
'email': email,
});
message.clear();
}
},
icon: Icon(Icons.send_sharp),
),
],
),
],
),
),
);
}
}
message.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class messages extends StatefulWidget {
String email;
messages({required this.email});
#override
_messagesState createState() => _messagesState(email: email);
}
class _messagesState extends State<messages> {
String email;
_messagesState({required this.email});
Stream<QuerySnapshot> _messageStream = FirebaseFirestore.instance
.collection('Messages')
.orderBy('time')
.snapshots();
#override
Widget build(BuildContext context) {
return StreamBuilder(
stream: _messageStream,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Text("something is wrong");
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView.builder(
itemCount: snapshot.data!.docs.length,
physics: ScrollPhysics(),
shrinkWrap: true,
primary: true,
itemBuilder: (_, index) {
QueryDocumentSnapshot qs = snapshot.data!.docs[index];
Timestamp t = qs['time'];
DateTime d = t.toDate();
print(d.toString());
return Padding(
padding: const EdgeInsets.only(top: 8, bottom: 8),
child: Column(
crossAxisAlignment: email == qs['email']
? CrossAxisAlignment.end
: CrossAxisAlignment.start,
children: [
SizedBox(
width: 300,
child: ListTile(
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.green,
),
borderRadius: BorderRadius.circular(10),
),
title: Text(
qs['email'],
style: TextStyle(
fontSize: 15,
),
),
subtitle: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
width: 200,
child: Text(
qs['message'],
softWrap: true,
style: TextStyle(
fontSize: 15,
),
),
),
Text(
d.hour.toString() + ":" + d.minute.toString(),
)
],
),
),
),
],
),
);
},
);
},
);
}
}
How should I read the phone number? I'm not sure how do we related both firebase authentication and cloud firestore.
If you have the information of the phone number you have to provide it to messages(email)
Also Widget names (like all class names) should begin with an uppercase
Something like:
class Messages extends StatefulWidget {
String email;
Messages({required this.email});
#override
_MessagesState createState() => _MessagesState(email: email);
}
class _MessagesState extends State<Messages> {
String email;
_MessagesState({required this.email});
Stream<QuerySnapshot> _messageStream = FirebaseFirestore.instance
.collection('Messages')
.orderBy('time')
.snapshots();
#override
Widget build(BuildContext context) {
return StreamBuilder(
stream: _messageStream,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Text("something is wrong");
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView.builder(
itemCount: snapshot.data!.docs.length,
physics: ScrollPhysics(),
shrinkWrap: true,
primary: true,
itemBuilder: (_, index) {
QueryDocumentSnapshot qs = snapshot.data!.docs[index];
DateTime time = qs['time'].toDate();
String message = qs['message'];
String messageEmail = qs['email'];
String messagePhoneNumber = qs['phoneNumber'];
return Padding(
padding: const EdgeInsets.only(top: 8, bottom: 8),
child: Column(
crossAxisAlignment: email == messageEmail
? CrossAxisAlignment.end
: CrossAxisAlignment.start,
children: [
SizedBox(
width: 300,
child: ListTile(
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.green,
),
borderRadius: BorderRadius.circular(10),
),
title: Text(
messageEmail == email ? email : messagePhoneNumber,
style: TextStyle(
fontSize: 15,
),
),
subtitle: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
width: 200,
child: Text(
message,
softWrap: true,
style: TextStyle(
fontSize: 15,
),
),
),
Text(
time.hour.toString() + ":" + time.minute.toString(),
)
],
),
),
),
],
),
);
},
);
},
);
}
}
As I said, it depends on your provided data if there is a phoneNumber
I am searching in ListView and I am getting search result in flitered list but when I am selecting the searched item in listview and clear the searchbox in the original list my selected item is deselected.
My original list is "rest" list in the code and filtered list is "filteredList used in code.
Help me to solve my issue as I am new to flutter.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
String stringValue="default";
String Currentdate;
const lightGrey = Color(0xff858585);
const darkGrey = Color(0xff404042);
const orange = Color(0xffff8500);
const blue = Color(0xff2f5597);
const skyblue=Color(0xffF1F5F9);
const darkblue=Color(0xffD4E7F9);
class AttendencePage2 extends StatefulWidget {
final String centernametext,batchname,date,centerid,batchid,accesstoken;
AttendencePage2(this.centernametext,this.batchname,this.date,this.centerid,this.batchid,this.accesstoken);
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return _AttendencePage2();
}
}
class _AttendencePage2 extends State<AttendencePage2> {
int i;
String str_accesstoken;
List rest;
List<Autogenerated> list= List<Autogenerated>();
List filteredlist;
TextEditingController controller = new TextEditingController();
bool isSelected = false;
List<int> indexList = new List();
bool longPressFlag = false;
void longPress() {
setState(() {
if (indexList.isEmpty) {
longPressFlag = false;
} else {
longPressFlag = true;
}
});
}
var mycolor=Colors.white;
bool checkVal = false;
bool checkVal2=false;
#override
void initState() {
super.initState();
getStringValuesSF();
StudentListRequest();
}
#override
Widget build(BuildContext context) {
// for (var i = 0; i < 50; i++) {
// indexList.add(Element(isSelected: false));
// }
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
systemNavigationBarColor: Colors.white, // navigation bar color
statusBarColor: Colors.black, // status bar color
));
return MaterialApp(
home: Scaffold(
appBar: AppBar(
centerTitle: true,
backgroundColor: orange,
title: Text('ATTENDENCE'),
),body:
Stack(
children: <Widget>[
Container(
color: Colors.white,
),
Container(
color: skyblue,
width: double.infinity,
height: 65,
padding: EdgeInsets.only(right: 20,left: 20,top: 10,bottom: 10),
child:Row(
children: <Widget>[
Container(
child:Column(children: <Widget>[
Text("Center Name",style: TextStyle(color: lightGrey,fontSize: 17)),
Container(
margin: EdgeInsets.only(top:5),
child:Text(widget.centernametext.toUpperCase(),style: TextStyle(color: Colors.black,fontSize: 13)),
),
],)
//child:
),
Spacer(),
Container(
child:Column(children: <Widget>[
Text("Batch",style: TextStyle(color: lightGrey,fontSize: 17),textAlign: TextAlign.left,),
Container(
margin: EdgeInsets.only(top:5),
child:Text(widget.batchname,style: TextStyle(color: Colors.black,fontSize: 13)),),
],)
),
Spacer(),
Container(
child:Column(children: <Widget>[
Text("Date",style: TextStyle(color: lightGrey,fontSize: 17)),
Container(
margin: EdgeInsets.only(top:5),
child:Text(widget.date,style: TextStyle(color: Colors.black,fontSize: 13)),
),
],)
),
Container(
margin: EdgeInsets.only(left: 10),
child: Image.asset('assets/grey_edit.png',width: 20,height: 25),
),
],
)
),
_searchBar(),
Container(
color: skyblue,
width: double.infinity,
height: 50,
margin: EdgeInsets.only(top:155,left: 10,right: 10),
padding: EdgeInsets.only(right: 20,left: 0,top: 10,bottom: 10),
child:Row(
children: <Widget>[
Container(
child: Checkbox(
value: checkVal,
onChanged: (bool value) {
setState(() {
checkVal = value;
if(checkVal==true){
isSelected=true;
}else{
isSelected=false;
}
});
} ),
),
Container(margin: EdgeInsets.only(top:5),
child:Column(children: <Widget>[
Text("Name",style: TextStyle(color: lightGrey,fontSize: 15)),
],)
),
Spacer(),
Container(margin: EdgeInsets.only(top:5),
child:Column(children: <Widget>[
Text(" ",style: TextStyle(color: lightGrey,fontSize: 15),textAlign: TextAlign.left,),
],)
),
Spacer(),
Container(margin: EdgeInsets.only(top:5),
child:Column(children: <Widget>[
Text("Level ",style: TextStyle(color: lightGrey,fontSize: 15)),
],)
),
Spacer(),
Container(margin: EdgeInsets.only(top:5),
child:Column(children: <Widget>[
Text("No. of class",style: TextStyle(color: lightGrey,fontSize: 15)),
],)
),
Spacer(),
Container(margin: EdgeInsets.only(top:5),
child:Column(children: <Widget>[
Text("Attend",style: TextStyle(color: lightGrey,fontSize: 15)),
],)
),
],
)
),
Container(
margin: EdgeInsets.only(top:205,left: 10,right: 10),
decoration: BoxDecoration(
border: Border.all(color: darkblue)
),
child: ListView.builder(
//addAutomaticKeepAlives: true,
itemCount: filteredlist==null?0:filteredlist.length,
// padding: const EdgeInsets.all(2.0),
itemBuilder: (context, index) {
return new CustomWidget(
selected:isSelected,
rest:filteredlist,
index: index,
longPressEnabled: longPressFlag,
callback: () {
longPress();
},
);
})
)])));
}
_searchBar() {
return Container(
child:Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
width: 350,
height: 40,
margin: EdgeInsets.only(left:20,top:90),
child:TextField(
decoration: InputDecoration(
contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
prefixIcon: new Padding(
padding: const EdgeInsets.only( top: 13, left: 0, right: 5, bottom: 13),
child: new SizedBox(
height: 2,
child: Image.asset('assets/search.png'),
),
),
labelText: "Search by name",
labelStyle: TextStyle(
color: lightGrey,
fontSize: 15
),
border: OutlineInputBorder( borderSide: BorderSide(color: lightGrey, width: 0.5),
borderRadius: BorderRadius.circular(5.0)),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: orange, width: 0.5),
borderRadius: BorderRadius.circular(5.0)
)),
controller: controller,
onChanged: (string){setState(() {
filteredlist=rest.where((f){
var dataName=f['student']['name'].toString().toLowerCase();
var dataName2=f['course']['level_no'].toString().toLowerCase();
return dataName.contains(string)||dataName2.contains(string);
}).toList();
}
);
},
)
),
],
)
);
}
Future<List<Autogenerated>> StudentListRequest() async {
String as=widget.accesstoken.toString();
var url = 'http://demo.neurapses.com:3032/students?center=5ca5ba30e0adb9c1839aa0d2&batch=5ca5c81597f8a03368df072c';
var response = await http.get(url,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer $as'
},
);
final int statusCode = response.statusCode;
if (statusCode < 200 || statusCode > 400 || json == null) {
throw new Exception("Error while fetching data");
} else {
setState(() {
var data = json.decode(response.body);
rest = data['docs'];
for(var rest in rest)
{
list.add(Autogenerated.fromJson(rest));
}
filteredlist=rest;
});
return list;
}
}
getStringValuesSF() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
str_accesstoken = prefs.getString('accesstoken');
}
}
class Autogenerated {
List<Docs> docs;
Autogenerated({this.docs});
Autogenerated.fromJson(Map<String, dynamic> json) {
if (json['docs'] != null) {
docs = new List<Docs>();
json['docs'].forEach((v) {
docs.add(new Docs.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.docs != null) {
data['docs'] = this.docs.map((v) => v.toJson()).toList();
}
return data;
}
}
class Docs {
Student student;
Docs(
{
this.student,
});
Docs.fromJson(Map<String, dynamic> json) {
student =
json['student'] != null ? new Student.fromJson(json['student']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.student != null) {
data['student'] = this.student.toJson();
}
return data;
}
}
class Student {
String name;
Student(
{
this.name,
});
Student.fromJson(Map<String, dynamic> json) {
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
return data;
}
}
class CustomWidget extends StatefulWidget {
final int index;
final bool longPressEnabled;
final VoidCallback callback;
final List rest;
bool selected;
CustomWidget({Key key, this.selected, this.rest, this.index, this.longPressEnabled, this.callback}) : super(key: key);
#override
_CustomWidgetState createState() => new _CustomWidgetState();
}
class _CustomWidgetState extends State<CustomWidget> {
final skyblue=Color(0xffF1F5F9);
#override
Widget build(BuildContext context) {
return new GestureDetector(
onLongPress: () {
widget.callback();
},
onTap: () {
if (widget.longPressEnabled) {
widget.callback();
}
},
child:Container(
margin: new EdgeInsets.only(top:5.0),
color: widget.selected ? Colors.grey[300]:Colors.white,
child:Row(children: <Widget>[
Flexible(
fit:FlexFit.loose,
child: ListTile(
contentPadding: EdgeInsets.only(left: 0.0, right: 0.0),
title:
Container(
child:Column(children: <Widget>[
Row(
children: <Widget>[
Container(
child: Checkbox(
onChanged: (val) {
setState(() {
widget.selected = !widget.selected;
});
},
value: widget.selected,
),
),
Container(
child:Container(width:80,child:Text(widget.rest[widget.index]['student']['name'], style: TextStyle(color: Colors
.black, fontSize: 13),
)),
),
Spacer(),
Container(
child: Text(widget.rest[widget.index]['course']['level_no'], style: TextStyle(color: Colors
.black, fontSize: 13),)
),
Spacer(),
Container(
child: Text(
"", style: TextStyle(color: Colors.black,
fontSize: 13),)
),
Spacer(),
Container(
child: Text("", style: TextStyle(color: Colors
.black, fontSize: 13),)
),
],
),
Container(
color: darkblue,
height: 0.7,
width: double.infinity,
),
]),
// onLongPress: toggleSelection,
))
)],),
));
}
}
Add Search Bar
TextField(
controller: editingController,
decoration: InputDecoration(
labelText: "Search",
hintText: "Search",
prefixIcon: Icon(Icons.search),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(25.0)))),
),
Code for UI showing a search bar and ListView with 1000 items
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'ListView with Search'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
TextEditingController editingController = TextEditingController();
final duplicateItems = List<String>.generate(10000, (i) => "Item $i");
var items = List<String>();
#override
void initState() {
items.addAll(duplicateItems);
super.initState();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: Container(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
onChanged: (value) {
},
controller: editingController,
decoration: InputDecoration(
labelText: "Search",
hintText: "Search",
prefixIcon: Icon(Icons.search),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(25.0)))),
),
),
Expanded(
child: ListView.builder(
shrinkWrap: true,
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
title: Text('${items[index]}'),
);
},
),
),
],
),
),
);
}
}