Hi i am new to flutter i need help in getting API data and display with a checkbox to select and deselect. i have used sample API database which contains the information of 10 users. I want to display Users Id, name, Username, company name and phone number as a card or list tile per user. I also want to assign single checkbox per card/list tile with check / uncheck functionality.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_application_http_get/example.dart';
import 'package:flutter_application_http_get/screen.dart';
import 'package:flutter_application_http_get/sunday_state.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Sunday(),
);
}
}
Here's My ApI Get method
class Sunday extends StatefulWidget {
const Sunday({Key? key}) : super(key: key);
@override
_SundayState createState() => _SundayState();
}
class _SundayState extends State<Sunday> {
var users = [];
Future getUserData() async {
var res =
await http.get(Uri.https("jsonplaceholder.typicode.com", "users"));
var jsonData = jsonDecode(res.body) as List;
setState(() {
users = jsonData;
});
}
@override
void initState() {
super.initState();
getUserData();
}
here's my build method
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("User Data"),
),
body: Container(
child: Card(
margin: EdgeInsets.all(20.0),
child: ListView.builder(
itemCount: users.length,
itemBuilder: (context, i) {
final post = users[i];
return Card(
elevation: 5,
child: Padding(
padding: const EdgeInsets.all(12.0),
child: ListView(shrinkWrap: true, children: [
// singlecheckbox(notification),
...notification.map(singlecheckbox).toList(),
Text("${post['id']}"),
Text("${post['name']}"),
])
here's my widget to toggle check box
final notification = [SundayCheckBoxState()];
void togglegroupcheckbox(bool? value) {
if (value == null) return;
setState(() {
// notification.value = value;
notification.forEach((element) => element.value = value);
});
}
Widget singlecheckbox(SundayCheckBoxState checkbox) {
return CheckboxListTile(
controlAffinity: ListTileControlAffinity.leading,
activeColor: Colors.green,
value: checkbox.value,
// title: Text('${users.last['name']}'),
onChanged: togglegroupcheckbox,
);
Aucun commentaire:
Enregistrer un commentaire