Flutter - Adding arrays to a widget list - arrays

I want to add all the data in the applicants list but it only adds the last data in the array. Sorry I am still new to flutter.
This is my code.
List<ApplicantsList> applicants;
Future <void> getApplicantInfo() async {
AuthService().getRequestorApplicants().then((val) async {
for (var i = 0; i < val.data.length; i++) {
var temp = val.data[i];
applicants = [
ApplicantsList(name: temp['parentname'], contact: temp['parentname'], location: temp['location'])
];
}
});
}
This is my ApplicantsList
class ApplicantsList {
String name;
String contact;
String location;
ApplicantsList({this.name, this.contact, this.location});
}
This is where I display applicants list.
Container(
child: StreamBuilder<Object>(
stream: null,
builder: (context, snapshot) {
return Container(
height: MediaQuery.of(context).size.height,
child: ListView(
shrinkWrap: true,
scrollDirection: Axis.vertical,
children: <Widget>[
Column(
children: applicants.map((e) => _PendingCardDonor(e.name, e.contact, e.location),).toList(),
),
],
));
}),
),

I realized it's because List is deprecated. So I just need to add [] like this one. List<ApplicantsList> applicants = [];

Related

How do I display fetched Data from MariaDB to a listview

So basically what i want to do is to display the data i get from my DB in a ListView, but I'm only able to show one attribute of my Object Device.
This my Class for device
class Devices {
final int iD;
final String location;
final String type;
Devices({required this.iD, required this.location, required this.type});
factory Devices.fromJson(Map<String, dynamic> json) {
return Devices(
iD: json['id'] as int,
location: json['Ort'] as String,
type: json['Typ'] as String);
}
}
The json i get from my PHP script looks like this
{"id":1,"Ort":"Wohnzimmer","Typ":"Sensor"}
Code to show my Class
class DeviceList extends StatelessWidget {
List<Devices> dList;
DeviceList({super.key, required this.dList});
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: dList.length,
itemBuilder: (context, index) {
// return Text(dList[index].location,
// style: const TextStyle(color: Colors.white, fontSize: 40));
return (ListTile(title: Text(dList[index].iD.toString())));
},
);
}
}
I want to show all attributes of my Class at the same and not only the iD of it, but i have no clue how to do it.
in ListTile widget you can display your data like this
ListView.builder(
itemCount: dList.length,
itemBuilder: (context, index) {
return Card(
elevation: 4,
child: ListTile(
leading: CircleAvatar(
child: Text("${dList[index].iD}"),
),
title: Text(dList[index].type),
subtitle: Text(dList[index].location),
),
);
},
),
which will look like this
there are a lot of other ways to display that data.
It depends on how you want to display the other attributes
if you want to use ListTile you probably want to make the use of the leading and trailing
return ListTile(
leading: Text(
dList[index].iD.toString(),
),
title: Text(
dList[index].location,
),
trailing: Text(
dList[index].type,
),
);
or use a Row inside the title, it's up to you

how to get the name Column from an ID foreign Key SQLITE?

I want to display the name of the home and away team in a listTile, I have a table that has two foreign keys, each one of them points to the ID of the team used on this game.
How can I display their name and not their ID in my tile please?
ListView(
children: snapshot.data!.map((match){
return Center(
child: Card(
child: Material(
elevation: 10.0,
child: ListTile(
tileColor: Colors.lightBlue,
title: Row(
children: [
Text(
(match.xidTeam).toString()
),
Text("-----"),
Text(match.scoreT),
Text("/"),
Text(match.scoreR),
Text("-----"),
Text(match.xidRival.toString()),
],
),
onTap: (){},
),
this is the query I am using:
Future<List<Matchs>> getMatches(teamId) async {
var dbCoach = await db;
var games = await dbCoach!.query('matchs',
orderBy: 'idMatch', where: 'xidTeam = ?', whereArgs: [teamId]);
List<Matchs> matches =
games.isNotEmpty ? games.map((e) => Matchs.fromMap(e)).toList() : [];
return matches;
}
and this is my controller:
Future<List<Matchs>> listMatchs() async{
final statAccess = DatabaseModel();
SharedPreferences sp = await _pref;
var teamId = sp.getInt('idTeam');
List<Matchs> matchs = await statAccess.getMatches(teamId);
return matchs;
}

How to understand to write gridview

I am a bit stuck with writing code. I have two lists, one "listAll" with numbers of all computers and "listBusy", which I get from JSON, with numbers of busy computers.
I want to write code, which displayed in gridview icons (green color) of all computers, but if computer is busy, he will have different icon (red color).
Can someone help with understanding how to write right code?
Thanks for helping!
List<String> pcAll = [
'S01',
'S02',
'S03',
'S04',
'S05',
'S06',
'S07',
'S08',
'S09',
'S10',
'S11',
'S12',
'S13',
'S14',
'S15',
'S16',
'S17',
'S18',
'S19'
];
List<String> pcBusy = [];
Future fetchDataStandart() async {
final urlAuth =
Uri.parse('http://XXX.XX.XXX.XXX/api/usersessions/activeinfo');
final response = await http
.get(urlAuth, headers: <String, String>{'authorization': basicAuth});
if (response.statusCode == 200) {
List listPc = List.from(json.decode(response.body)['result']);
pcBusy.clear();
for (int i = 0; i < listPc.length; i++) {
return pcBusy.add(listPc[i]['hostName']);
}
print(pcBusy);
} else {
throw Exception('Error');
}
}
Modified my code a little, not working
lass _EvrokoStandartScreenState extends State<EvrokoStandartScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text(
'ЕВРОКО Стандарт зал',
),
),
body: FutureBuilder(
future: getDataStandart(),
builder: (context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
} else {
return ComputerGrid();
}
},
));
}
}
class ComputerGrid extends StatelessWidget {
const ComputerGrid();
#override
Widget build(BuildContext context) {
return GridView.builder(
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 200,
childAspectRatio: 3 / 2,
crossAxisSpacing: 20,
mainAxisSpacing: 20,
),
itemCount: pcAll.length,
itemBuilder: (BuildContext context, index) {
return GridTile(
child: Container(
color: pcBusy.contains(pcAll[index]) ? Colors.red : Colors.green,
child: Text(
pcBusy[index],
),
),
);
},
);
}
}
[![Error][1]][1]
[1]: https://i.stack.imgur.com/keUZf.png
Right, you have the right tools for this job. How I would do it, is as follows.
class ComputerGrid extends StatelessWidget {
const ComputerGrid();
#override
Widget build(BuildContext context) {
/// Assuming you store your lists and other logic in some state file
return GridView.builder(
/// Options to change the layout and look of your items.
/// Play around with this a bit.
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 200,
childAspectRatio: 3 / 2,
crossAxisSpacing: 20,
mainAxisSpacing: 20,
),
/// You want as many items as there are entries in your listPc list
itemCount: listPc.length,
/// Building the actual items
itemBuilder: (BuildContext context, index) {
/// My example is barebones, play around with it to customize it
return GridTile(
child: Container(
/// Change the color depending on whether the computer is in the busy list
color: pcBusy.contains(listPc[index]['hostName'])
? Colors.red
: Colors.green,
child: Text(
/// Show the number of the computer at the current index.
listPc[index]['hostName'],
),
),
);
},
);
}
}
There's also a further optimization you can make in your for loop. You seem to have a background in JavaScript, and I think the for loop in Dart is much more elegant. The for loop below does the exact same as the one you have in your own code snippet.
for (final pc in listPc) {
pcBusy.add(pc['hostName']);
continue;
}

Build Data Back to ListView Builder [Flutter]

The existing code shows a list of buttons of varying interests. Users can tap to select which interests they prefer.
However, if the user has already selected their interests beforehand and comes back to this page, it's illogical to get the users to choose from a fresh state again.
I want to repopulate what the users have previously chosen and reflect back on the screen as chosen (which = widget.viewInterest.isChosen). The color of container will be Color(0xff0B84FE), & color of text is Colors.yellow, as seen in the code below.
Let's say user has chosen this list
List UserInterests = [
"☕ Coffee",
"🎭 Theaters",
];
QUESTION: How to make containers that contain these strings bool true (which is widget.viewInterest.isChosen), similar to when users have tapped on the respective buttons?
Attached is truncated code:
final List<String> artsInterests = [
"📸 Photography",
"🎭 Theaters",
"🖼️ Exhibitions",
"📐 Architecture",
"🍳‍ Cooking",
"☕ Coffee",
"🖍️ Design",
"👗 Fashion",
"📚 Reading",
"💃🏽 Dance",
"🏺 Pottery",
"🎨 Drawing",
"💋 Beauty",
"📖 Journalling",
];
StatelessWidget shortened
final List<String> artsInterests;
shortened
child: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.all(1),
itemCount: artsInterests.length
itemBuilder: (context, int index) {
return Interests2(AvailableInterestChosen(
artsInterests[index],
isChosen: false,
));
brackets...
child: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.all(1),
itemCount: artsInterests.length - 7,
itemBuilder: (context, int index) {
return Interests2(AvailableInterestChosen(
artsInterests[7 + index],
isChosen: userChosenInterests
.contains(artsInterests[7 + index]),
));
closing brackets...
List<String> chosenArtsInterests = [];
List<String> UserInterests = [
"☕ Coffee",
"🎭 Theaters",
];
class Interests2 extends StatefulWidget {
final AvailableInterestChosen viewInterest;
Interests2(this.viewInterest);
String id = 'Interests2';
#override
Interests2State createState() => Interests2State();
}
class Interests2State extends State<Interests2> {
#override
Widget build(BuildContext context) {
final height = MediaQuery.of(context).size.height;
final width = MediaQuery.of(context).size.width;
Container container = Container(
decoration shortened
decoration: BoxDecoration(
color: widget.viewInterest.isChosen && chosenInterests.length < 9
? Color(0xff0B84FE)
: Colors.white.withOpacity(0.87),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.69),
spreadRadius: 1,
blurRadius: 3,
offset: Offset(0, 1), // changes position of shadow
),
],
borderRadius: BorderRadius.circular(9),
),
child: Text(
'${widget.viewInterest.title}',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w600,
color: widget.viewInterest.isChosen && chosenInterests.length < 9
? Colors.white
: Colors.black),
));
if (widget.viewInterest.isChosen && chosenInterests.length < 9) {
chosenArtsInterests.add('${widget.viewInterest.title}');
print(chosenArtsInterests);
} else {
chosenArtsInterests.remove('${widget.viewInterest.title}');
print(chosenArtsInterests);
}
return GestureDetector(
onTap: () {
setState(() {
widget.viewInterest.isChosen = !widget.viewInterest.isChosen;
});
},
child: container,
);
}
}
class AvailableInterestChosen {
bool isChosen;
String title;
AvailableInterestChosen(this.title, {this.isChosen = false});
}
For the buttons to depict UI that shows they are chosen, my guess is something like
for (string i in UserInterests) setState ((){widget.viewInterest.isChosen})
But in regards to where to put it or the exact code, I'm lost. If anyone has some experience or similar resources to share so I can read on it, that will be great!
How about checking the element is in the UserInterests list?
Something like this may work,
AvailableInterestChosen(
artsInterests[index],
isChosen: UserInterests.contains(artsInterests[index]),
)

passing API data from page 1 to another dart page on flutter

page that already has data from the API, then I want to send the API data to the next page.
example: when we click the food list, a description of the food that is clicked will appear or when we click the data on another page, it is more detailed than the data on the list
The following is the code from the start page :
var notifikasiSiswa = [];
//====================== Fungsi ListView ================================
class _NotifikasiSiswaState extends State<NotifikasiSiswa> {
Future<SharedPreferences> _sprefs = SharedPreferences.getInstance();
int id;
#override
Future<Null> getData() async {
final SharedPreferences prefs = await _sprefs;
int data = prefs.getInt('id');
this.setState(() {
id = data ;
});
// counter = data;
// api coba dsni
NotifikasiSiswaMo.getPengumuman(id.toString()).then((value) {
notifikasiSiswa = value;
this.setState(() {
notifikasiSiswa = value;
});
print("muncul");
});
// print(token);
}
#override
void initState() {
super.initState();
setState(() {
getData();
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Materi Siswa"),),
body: ListView.builder( // Auto Scroll Jika Data yang dimunculkan banyak
reverse: true,
itemCount: notifikasiSiswa.length,
itemBuilder: (context, index){
return Center(
child: Padding(
padding: EdgeInsets.only(left: 20.0, right: 20.0, top: 15.0 ),
child: Stack(
children: <Widget>[
Container(
height: 100,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(_borderRadius),
gradient: LinearGradient(
colors: [Colors.white, Colors.white],
begin: Alignment.topLeft,
end: Alignment.bottomRight),
)
),
Positioned.fill(child: InkWell(
splashColor: Colors.blue.withAlpha(30),
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context) {
return NotifikasiSiswaDetail(
s_date : notifikasiSiswa[index].date,
s_title : notifikasiSiswa[index].title,
s_message :notifikasiSiswa[index].message
);
},
));
},
child: Row(
children: <Widget>[
Expanded(
child:
Center(
child: Icon(Icons.notifications_active))
),
Expanded(
flex: 4,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start, //Vertical dengan posisi aligmn start
children: <Widget>[
Text(notifikasiSiswa[index].date ?? "00/00/00",
style: TextStyle(
color: Colors.black45,
fontWeight: FontWeight.w500),),
SizedBox(
height: 6.0,
),
how on the next page ?
final List args = ModalRoute.of(context).settings.arguments;Provided that I understood your question correctly, you can pass data to a new page using the arguments parameter in your Navigator.pushNamed().
Navigator.pushNamed(context, '/newPage', arguments: /* data you want to pass */);
To access this data from the new page you can use this line inside its build method.
final args = ModalRoute.of(context).settings.arguments;
You can learn more about this here: https://flutter.dev/docs/cookbook/navigation/navigate-with-arguments
You have (at least) two options here:
Save the data in the state. If the data is not so big and complex, you can carry it around via state.
Make a new request. If you need a lot more details than just title and description such as comments, like, shares, etc. then you better make a new request. Yes, it costs you more in terms of bandwidth and also money, but it gives you more room to work with.

Resources