Json is not responding - android

i am trying to initialize json data in my widget but for some reason, it is not responding. i am pretty new to dealing with json called locally and this is one of them. i have already done all the necessary things like creating the file to put the data and passing it through the pubspec. still it is not responding. here is the json data
[
{
"_id":"636e0ce55270d648e9a5248a",
"index":0,
"guid":"58e73438-27fa-48bf-8127-ff4e42beaac5",
"isActive":true,
"price":"$252.77",
"name":"James Lewis Blue Ledis",
"type":"dress",
"image":"https://images.unsplash.com/photo-1539008835657-9e8e9680c956?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=687&q=80"
},
{
"_id":"636e0ce573d4e1ce44e5a5a9",
"index":1,
"guid":"e1d93cfe-b15a-4969-97e0-3b6b9ae967d0",
"isActive":false,
"price":"$289.88",
"name":"Blue FLower Shoe",
"type":"apparel",
"image":"https://images.unsplash.com/photo-1543163521-1bf539c55dd2?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=880&q=80"
},
{
"_id":"636e0ce522bd392da7b43d2e",
"index":2,
"guid":"0ee56032-db50-44c3-9234-5e213b8fde22",
"isActive":false,
"price":"$452.81",
"name":"Yellow Blight Bag",
"type":"bag",
"image":"https://images.pexels.com/photos/934673/pexels-photo-934673.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
"recommended":true
},
{
"_id":"636e0ce5fdf98a105a5c14cb",
"index":3,
"guid":"fee6217c-ee7f-4e3e-91cc-24dfd91d6cfc",
"isActive":true,
"price":"$244.91",
"name":"Black meter dress",
"type":"dress",
"image":"https://images.unsplash.com/photo-1550639525-c97d455acf70?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=726&q=80"
},
{
"_id":"636e0ce5036de010a96ab185",
"index":4,
"guid":"2d9e8b22-90c1-4979-b904-2cc164626e10",
"isActive":false,
"price":"$335.17",
"name":"Dynamic Pink Lobre",
"type":"bag",
"image":"https://images.unsplash.com/photo-1566150905458-1bf1fc113f0d?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1171&q=80"
},
{
"_id":"636e0ce52e2a60eed71c79b6",
"index":5,
"guid":"32db02a5-a12d-4f3e-a601-787211734ab1",
"isActive":false,
"price":"$414.69",
"name":"Gucci Flems Onyx",
"type":"bag",
"image":"https://images.unsplash.com/photo-1548036328-c9fa89d128fa?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1169&q=80"
},
{
"_id":"636e0ce52f14c39bb8366650",
"index":6,
"recommended":true,
"guid":"1a0c388c-2ac7-4a49-85ba-50b12bc08f28",
"isActive":true,
"price":"$293.63",
"name":"705 California",
"type":"apparel",
"image":"https://images.unsplash.com/photo-1618354691229-88d47f285158?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=715&q=80"
},
{
"_id":"636e0ce56b57e56f54676302",
"index":7,
"guid":"956527b1-c9d8-4c18-a6ef-e4b1dcd76640",
"isActive":false,
"price":"$293.57",
"name":"Mid-week flavors",
"type":"apparel",
"image":"https://images.unsplash.com/photo-1560769629-975ec94e6a86?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=764&q=80"
},
{
"_id":"636e0ce56c0ed15b28297895",
"index":8,
"guid":"119db62a-eaba-493f-b73a-5dcba04b69c1",
"isActive":false,
"price":"$348.63",
"name":"Hermes Coysx",
"type":"bag",
"image":"https://images.unsplash.com/photo-1594223274512-ad4803739b7c?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=757&q=80"
},
{
"_id":"636e0ce58d2cbb1e636f1829",
"index":9,
"guid":"40011d30-d06d-4a72-b119-0826dc79c138",
"isActive":true,
"price":"$337.91",
"name":"Kirsten Gilliam",
"type":"dress",
"image":"https://images.unsplash.com/photo-1543163521-1bf539c55dd2?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=880&q=80"
},
{
"_id":"636e0ce5713679af9a884699",
"index":10,
"guid":"f5dbfba4-fbe2-475b-98fc-36ff42daad91",
"isActive":false,
"price":"$436.62",
"recommended":true,
"name":"Outcast white",
"type":"t-shirt",
"image":"https://images.unsplash.com/photo-1527719327859-c6ce80353573?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=764&q=80"
},
{
"_id":"636e0ce5578fa1d92624204f",
"index":11,
"guid":"805df707-3833-4e5f-9e09-0c59053750cb",
"isActive":false,
"price":"$493.15",
"name":"Peace Skull",
"type":"t-shirt",
"image":"https://images.unsplash.com/photo-1503341504253-dff4815485f1?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=687&q=80"
},
{
"_id":"636e0ce5bd29b6bd570aef00",
"index":12,
"guid":"32e75d5c-ea59-4c23-8d85-29dd37040a7d",
"isActive":false,
"price":"$350.71",
"name":"Louis Vuiton Brown bag",
"type":"bag",
"image":"https://images.pexels.com/photos/3661622/pexels-photo-3661622.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
},
{
"_id":"636e0ce505794be5900eb9ad",
"index":13,
"guid":"44aa2a9a-e1c9-4004-b681-ce246e5a8ee4",
"isActive":true,
"price":"$271.21",
"name":"Impulso Supreme",
"type":"t-shirt",
"recommended":true,
"image":"https://images.unsplash.com/photo-1627933540891-1fb6a397c89b?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=764&q=80"
}
]
and this is where it is being called
class ExploreCollections extends StatefulWidget {
const ExploreCollections({Key? key}) : super(key: key);
#override
State<ExploreCollections> createState() => _ExploreCollectionsState();
}
class _ExploreCollectionsState extends State<ExploreCollections> {
final List _items = [];
Future<void> readJson() async{
final String response = await rootBundle.loadString('assets/model/clothes.json');
final data = await json.decode(response);
}
#override
void initState() {
_items.shuffle();
super.initState();
}
int _activeIndex = 0;
final List<Widget> _images = [
Stack(
children: [
Image.asset('assets/images/image 10.png'),
Padding(
padding: const EdgeInsets.only(left: 55.0, top: 230),
child: Text(
'Luxury \n Fashion \n &Accessories'.toUpperCase(),
style: TextStyle(
fontFamily: 'Bodoni',
fontSize: 40,
fontWeight: FontWeight.w500,
color: Colors.grey.shade700
),
),
),
Padding(
padding: const EdgeInsets.only(top: 400.0),
child: Center(
child:SvgPicture.asset('assets/iconImages/Button.svg'),
),
),
],
),
Stack(
children: [
Image.asset('assets/images/leeloo.jpeg'),
],
),
Stack(
children: [
Image.asset('assets/images/ayaka.jpeg'),
],
),
];
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: 5,
child: Column(
children: [
Stack(
children: [
CarouselSlider.builder(
options: CarouselOptions(
viewportFraction: 1,
aspectRatio: 1.8,
height: MediaQuery.of(context).size.height*0.8,
autoPlay: false,
initialPage: 0,
enableInfiniteScroll: false,
enlargeCenterPage: true,
onPageChanged: (index, reason){
setState(() {
_activeIndex = index;
});
}
),
itemCount: _images.length,
itemBuilder: (BuildContext context, int index, int realIndex) {
return GestureDetector(
onTap: (){
Navigator.of(context).pushNamedAndRemoveUntil(BlackScreen.routeName, (route) => false);
},
child: _images[index]);
},
),
Padding(
padding: const EdgeInsets.only(top: 565.0),
child: Center(
child: buildIndicator(),
),
),
],
),
SvgPicture.asset('assets/images/Title.svg'),
const SizedBox(
height: 10,),
TabBar(
indicator: CircleTabIndicator(color: Colors.redAccent, radius: 3),
tabs: [
Tab(child: Text('All',style: TextStyle(color: Colors.grey.shade600),),),
Tab(child: Text('Apparel',style: TextStyle(color: Colors.grey.shade600),),),
Tab(child: Text('Dress',style: TextStyle(color: Colors.grey.shade600),),),
Tab(child: Text('Tshirt',style: TextStyle(color: Colors.grey.shade600),),),
Tab(child: Text('Bag',style: TextStyle(color: Colors.grey.shade600),),),
]
),
Container(
height: 60,
child: TabBarView(
children: [
All(items: _items),
Center(child: Text('Apparel'),),
Center(child: Text('Dress'),),
Center(child: Text('Tshirt'),),
Center(child: Text('Bag'),),
]
),
)
],
),
);
}
i finally passed it to the 'All class'
class All extends StatelessWidget {
final List items;
const All({Key? key, required this.items}) : super(key: key);
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, index){
return Text(items[index]['name']);
});
}
}

As a first step you should change the type of your _list variable to Map<String,dynamic>
And change readJson method return type
Future<Map<String,dynamic>> readJson() async{
final String response = await rootBundle.loadString('assets/model/clothes.json');
return await json.decode(response);
}
And call readJson in initState like so
#override
void initState() {
WidgetsBinding.instance.addPostFrameCallback((_) async {
readJson().then((value) =>_items = value);
});
super.initState();
}
This should do the trick

Related

How to make page transition when use bottomNavigationBar in flutter

I use a basic bottomNavigationBar and now it shows just page without any transition,i want to use page transition when tap different bottomNavigationBars item.
Use IndexedStack Widget
int _currentIndex = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: IndexedStack(
index: _currentIndex,
children: const [
HomePage(),
SettingsPage(),
],
),
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: (int index) => setState(() => _currentIndex = index),
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
BottomNavigationBarItem(icon: Icon(Icons.settings), label: 'Settings'),
],
),
);
}
use PageView or TabView
Check this article
List pages = [
HomeScreen(),
DiscoverScreen(),
Container(),
MessageScreen(),
ProfileScreen(),
];
Scaffold(
body: pages.elementAt(current!),
bottomNavigationBar: BottomNavigationBar(
currentIndex: widget.current!,
unselectedItemColor: Colors.black,
selectedItemColor: Colors.green,
showSelectedLabels: true,
showUnselectedLabels: true,
onTap: (val) {
setState(() {
current = val;
});
Bottom Nav Transition With Persisting Ui
import 'package:flutter/material.dart';
class BottomNavTransitionWithPersistingUi extends StatefulWidget {
const BottomNavTransitionWithPersistingUi({Key? key}) : super(key: key);
#override
State<BottomNavTransitionWithPersistingUi> createState() => _BottomNavTransitionWithPersistingUiState();
}
class _BottomNavTransitionWithPersistingUiState extends State<BottomNavTransitionWithPersistingUi> {
late PageController _pageController;
late List<Widget> _tabBody;
int _currentIndex = 0;
#override
void initState() {
super.initState();
_pageController = PageController(
initialPage: 0,
keepPage: true, // for ui state
);
_tabBody = [
const NavHomeView(key: PageStorageKey("NavHomeView")),
const NavMoreView(key: PageStorageKey("NavMoreView")),
];
}
#override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: _bottomNavigationBarItems,
body: PageView(
controller: _pageController,
onPageChanged: _onPageChanged,
children: _tabBody,
),
);
}
Widget get _bottomNavigationBarItems => BottomNavigationBar(
type: BottomNavigationBarType.fixed,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.menu),
label: 'More',
),
],
currentIndex: _currentIndex,
selectedItemColor: Colors.red,
elevation: 0.1,
unselectedItemColor: Colors.grey,
enableFeedback: true,
onTap: _onNavBarTapped,
);
void _onNavBarTapped(int index) {
setState(() {
_currentIndex = index;
});
_pageController.animateToPage(
index,
duration: const Duration(milliseconds: 500),
curve: Curves.easeOut,
);
}
void _onPageChanged(int index) {
setState(() {
_currentIndex = index;
});
}
}
class NavHomeView extends StatelessWidget {
const NavHomeView({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return ListView(
children: [
Container(
height: 500,
color: Colors.purple,
),
Container(
height: 500,
color: Colors.blue,
),
Container(
height: 500,
color: Colors.grey,
),
],
);
}
}
class NavMoreView extends StatelessWidget {
const NavMoreView({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return ListView(
children: [
Container(
height: 500,
color: Colors.red,
),
Container(
height: 500,
color: Colors.green,
),
Container(
height: 500,
color: Colors.amber,
),
],
);
}
}

flutter future builder keeps loading one-to-many relationship

im tring to view tasks on alone screen from data using rest api dart django
with project_id its one-to-many relationship project has many tasks so i want to dispay the tasks when i click on project widget using future builder
Edit :i found the problem check my answer below
here is usage of future builder and task list
import 'package:flutter/material.dart';
import 'package:project/model/task_model.dart';
import 'package:project/project_dtetailForTest.dart';
import 'package:provider/provider.dart';
import 'new_project.dart';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
class TaskById extends StatefulWidget {
//const TaskById({ Key? key }) : super(key: key);
final int project_id;
//final Task task =Task();
TaskById({required this.project_id}):super();
#override
State<TaskById> createState() => _TaskByIdState();
}
class _TaskByIdState extends State<TaskById> {
#override
Widget build(BuildContext context) {
final taskP= Provider.of<TaskProvider>(context);
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
elevation: 0,
bottom: PreferredSize(
child: Container(
color: const Color(0xff94adb4),
height: 2,
width: 320,
),
preferredSize: const Size.fromHeight(4.0)),
centerTitle: true,
backgroundColor:const Color(0xff076792),
title: const Text(
'Project1',
style: TextStyle(color: Colors.white,
fontSize: 35,
fontWeight:FontWeight.w700,
shadows: [
Shadow(
color: Color(0xa6A2B6D4),
blurRadius:20),
] ),
),
leading: IconButton(
onPressed: () {
Navigator.pop(context);
},
icon: const Icon(
Icons.arrow_back,
size: 44,
),
),
actions:[Container(padding: const EdgeInsets.fromLTRB(0, 0, 6, 3),
child: IconButton(
color:Colors.white ,
icon: const Icon(
Icons.search,
size: 44,
),
onPressed: () {},
),
),]
),
//TaskProvider(){
// this.fetchTask();
// }
body: FutureBuilder(
future: TaskProvider().fetchTask(widget.project_id),
builder: (context, snapshot){
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData && snapshot is List<Task>
?TaskList(task:snapshot.data as List<Task>)
:Center(child: CircularProgressIndicator());
}),
// FutureProvider(
// create: (context) => TaskProvider().fetchTask() ,
// initialData: [CircularProgressIndicator()],
// child:Center(child: Consumer<Task>(
// builder: (context, task, widget) {
// return (taskP !=null) ? Column(
// children: [
// Row(
// children: const [
// Padding(padding: EdgeInsets.all(7),
// child: Padding(
// padding: EdgeInsets.fromLTRB(24,10,10,8),
// child: Text('Project1',
// style: TextStyle(
// color: Color(0xff076792),
// fontSize: 40,
// fontWeight: FontWeight.w600
// ),
// ),
// ),
// ),
// ],
// ),
// // dynamic list
// Expanded(
// child: ListView.builder(
// itemCount: taskP.task.length ,
// itemBuilder: (BuildContext context, int index) {
// return Padding(
// padding: const EdgeInsets.fromLTRB(28, 12, 28, 0),
// child: GestureDetector(
// onTap: () {
// Navigator.push(context, MaterialPageRoute(builder: (context) => projectDetails()));
// },
// child: Card(child:Container(padding: const EdgeInsets.fromLTRB(18,8,9,4),
// width: 100,
// height: 100,
// decoration: BoxDecoration(
// borderRadius: BorderRadius.circular(19.0),
// color: const Color(0xff076792),
// boxShadow: const [
// BoxShadow(color: Colors.black, spreadRadius: 1),
// BoxShadow(color: Color(0xa6A2B6D4),
// offset: Offset(7,5),
// blurRadius:20),
// ],
// ),
// child: Column(children: [
// Row(mainAxisAlignment: MainAxisAlignment.start,
// children: [
// Text('Starting '+taskP.task[index].start.toString(),style:
// const TextStyle(color: Color.fromARGB(255, 133, 186, 202),fontSize: 18,),
// ),
// ],
// ),
// const Spacer(),
// Row(mainAxisAlignment: MainAxisAlignment.center,
// children: [
// Text(taskP.task[index].title??'',style:
// const TextStyle(color: Colors.white,fontSize: 34,)),
// ],
// ),
// const Spacer(),
// Row(mainAxisAlignment: MainAxisAlignment.end,
// children: [
// Text('Ending '+taskP.task[index].end.toString(),style:
// const TextStyle(color: Color.fromARGB(255, 133, 186, 202),
// fontSize: 18,
// )),
// ],
// ),
// ]),
// ),),
// ),
// );
// }),
// )
// ],
// )
// : CircularProgressIndicator();
// },
// ) ,
// )
// // widget.project_id),
// // builder: (context, snapshot){
// // if (snapshot.hasError) print(snapshot.error);
// // return snapshot.hasData
// // ? TaskList(taskP: snapshot.data)
// // : Center(child: CircularProgressIndicator());
// // }),
// )
);
}
}
class TaskList extends StatelessWidget {
final List <Task> task;
TaskList({Key? key, required this.task}) : super(key: key);
#override
Widget build(BuildContext context) {
final taskP= Provider.of<TaskProvider>(context );
// TODO: implement build
return Column(
children: [
Row(
children: const [
Padding(padding: EdgeInsets.all(7),
child: Padding(
padding: EdgeInsets.fromLTRB(24,10,10,8),
child: Text('Project1',
style: TextStyle(
color: Color(0xff076792),
fontSize: 40,
fontWeight: FontWeight.w600
),
),
),
),
],
),
// dynamic list
Expanded(
child: ListView.builder(
itemCount: taskP.task.length ,
itemBuilder: (BuildContext context, int index) {
return Padding(
padding: const EdgeInsets.fromLTRB(28, 12, 28, 0),
child: GestureDetector(
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => projectDetails()));
},
child: Card(child:Container(padding: const EdgeInsets.fromLTRB(18,8,9,4),
width: 100,
height: 100,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(19.0),
color: const Color(0xff076792),
boxShadow: const [
BoxShadow(color: Colors.black, spreadRadius: 1),
BoxShadow(color: Color(0xa6A2B6D4),
offset: Offset(7,5),
blurRadius:20),
],
),
child: Column(children: [
Row(mainAxisAlignment: MainAxisAlignment.start,
children: [
Text('Starting '+taskP.task[index].start.toString(),style:
const TextStyle(color: Color.fromARGB(255, 133, 186, 202),fontSize: 18,),
),
],
),
const Spacer(),
Row(mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(taskP.task[index].title??'',style:
const TextStyle(color: Colors.white,fontSize: 34,)),
],
),
const Spacer(),
Row(mainAxisAlignment: MainAxisAlignment.end,
children: [
Text('Ending '+taskP.task[index].end.toString(),style:
const TextStyle(color: Color.fromARGB(255, 133, 186, 202),
fontSize: 18,
)),
],
),
]),
),),
),
);
}),
)
],
);
}
}
here the api and model of task
// To parse this JSON data, do
//
// final task = taskFromJson(jsonString);
import 'dart:collection';
import 'dart:core';
import 'package:flutter/foundation.dart';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
//List<Task> taskFromJson(String str) => List<Task>.from(json.decode(str).map((x) => Task.fromJson(x)));
//String taskToJson(List<Task> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Task {
String? url;
int? id;
String? owner;
String? project;
String? title;
DateTime? start;
DateTime? end;
String? desc;
int? project_id;
Task(
{this.url,
this.id,
this.owner,
this.project,
this.title,
this.start,
this.end,
this.desc,
this.project_id});
factory Task.fromJson(Map<String, dynamic> json) => Task(
url :json["url"],
id: json["id"],
owner: json["owner"],
project: json["project"],
title: json["title"],
start: DateTime.parse(json["start"]),
end: DateTime.parse(json["end"]),
desc: json["desc"],
project_id: json["project_id"],
);
Map<String, dynamic> toJson() => {
"url": url,
"id": id,
"owner": owner,
"project": project,
"title": title,
"start": start?.toIso8601String(),
"end": end?.toIso8601String(),
"desc": desc,
"project_id": project_id,
};
}
class TaskProvider with ChangeNotifier{
TaskProvider(){
this.fetchTask();
}
List<Task> _task = [];
List<Task> get task {
return [..._task];
}
void addTask(Task task) async {
final response = await http.post(Uri.parse('http://mostafahamed.pythonanywhere.com/project/task'),
headers: {"Content-Type": "application/json"}, body: json.encode(task));
if (response.statusCode == 201) {
task.id = json.decode(response.body)['id'];
_task.add(task);
notifyListeners();
print('suceeed add ed task');
print(response.body);
}else{
print(response.body);
print('failed add ed task');
}
}
void deleteTask(Task task) async {
final response =
await http.delete(Uri.parse('http://mostafahamed.pythonanywhere.com/project/task${task.id}/'));
if (response.statusCode == 204) {
_task.remove(task);
notifyListeners();
}
}
Future<List<Task>> fetchTask([project_id]) async{
final response = await http
.get(Uri.parse('http://mostafahamed.pythonanywhere.com/tasks/?format=json'));
if (response.statusCode==200){
var data = json.decode(response.body)as List;
_task=data.map<Task>((json) => Task.fromJson(json)).toList();
notifyListeners();
print('sucess view task list');
print(response.body);
return _task;
}
else {
print(response.body);
print(response.statusCode);
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load tasks');
}
}
}
when i click on project wiget the screen keeps loading
I removed a condition && snapshot is List from future builder
and it works perfectly but
make sure to prevent the use of future builder if you have changeable values as future builder fetch data once I'm right now working to convert future builder into stream builder
if u have the same problem make sure all the types are the same
good luck to you all : )

GridView in Flutter

I'm working on a flutter project and I made a GridView with images and titles but I want the title to be outside the square, If I make padding they give this error BOTTOM OVERFLOWED BY 32 PIXELS. Any help is highly appreciated.
this is my code :
Card makeDashboardItem(String title, String img, int index) {
return Card(
elevation: 2,
margin: const EdgeInsets.all(3),
child: Container(
child: InkWell(
onTap: () {
setState(() {
isLoading = true;
});
_splitScreen2(index);
},
child: Column(
children: <Widget>[
const SizedBox(height: 10),
Center(
child: Image.asset(img,
alignment: Alignment.center),
),
const SizedBox(height: 1),
Center(
child: Text(
title,
style: const TextStyle(
fontSize: 13,
color: Colors.black,
),
),
),
],
),
),
),
);
}
Check DartPad
The Main problem was overflow so we wrap Expanded widget on Image widget.
Nb: Remove Expanded widget from Image widget You can see the difference
CardWidget
class ItemWidget extends StatelessWidget {
var data;
ItemWidget(this.data, {Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
height: 150,
child: Card(
child: Column(
children: [
Expanded(
child: Container(
height: 125,
child: Image.network(
data["Image"],
alignment: Alignment.center,
fit: BoxFit.cover,
),
),
),
Center(
child: Text(
data["Name"],
style: TextStyle(fontSize: 12),
))
],
),
),
);
}
}
Fullcode
import 'package:flutter/material.dart';
runApp(
MaterialApp(debugShowCheckedModeBanner: false, home: MyApp()),
);
}
class MyApp extends StatefulWidget {
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
var list = [
{
"Name": "ElectroniQues",
"Image":
"https://ecommerce.ccc2020.fr/wp-content/uploads/2020/10/electronic-gadgets.jpeg"
},
{
"Name": "Accessories",
"Image":
"https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/classic-accessories-1516305397.jpg"
},
{
"Name": "Hommes",
"Image":
"https://teja12.kuikr.com/is/a/c/880x425/gallery_images/original/cf5d08bff955e71.gif"
},
{
"Name": "Femmes",
"Image":
"https://cdn.pixabay.com/photo/2013/07/13/14/08/apparel-162192_1280.png"
},
{
"Name": "Enfants",
"Image": "https://images.indianexpress.com/2019/09/toys.jpg"
},
{
"Name": "Sunglasses",
"Image": "https://m.media-amazon.com/images/I/51zEsraniRL._UX569_.jpg"
},
{
"Name": "ElectroniQues",
"Image":
"https://ecommerce.ccc2020.fr/wp-content/uploads/2020/10/electronic-gadgets.jpeg"
},
{
"Name": "Accessories",
"Image":
"https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/classic-accessories-1516305397.jpg"
},
{
"Name": "Hommes",
"Image":
"https://teja12.kuikr.com/is/a/c/880x425/gallery_images/original/cf5d08bff955e71.gif"
},
{
"Name": "Femmes",
"Image":
"https://cdn.pixabay.com/photo/2013/07/13/14/08/apparel-162192_1280.png"
},
{
"Name": "Enfants",
"Image": "https://images.indianexpress.com/2019/09/toys.jpg"
},
{
"Name": "Sunglasses",
"Image": "https://m.media-amazon.com/images/I/51zEsraniRL._UX569_.jpg"
},
];
var column = Column(mainAxisAlignment: MainAxisAlignment.start, children: [
...list.map((e) {
return GestureDetector(onTap:(){},child: ItemWidget(e));
}).toList()
]);
return MaterialApp(
debugShowCheckedModeBanner: false,
home: SafeArea(
child: Row(
children: [
SideWidget(),
Expanded(
child: Scaffold(
bottomNavigationBar: buildBottomNavigationBar(),
body: Padding(
padding: const EdgeInsets.only(top: 18.0),
child:
// column
GridView.count(
crossAxisCount: 3,
mainAxisSpacing: 2,
crossAxisSpacing: 2,
children: [
...list.map((e) {
return InkWell(onTap:(){},child: ItemWidget(e));
}).toList()
],
),
),
),
),
],
),
),
);
}
BottomNavigationBar buildBottomNavigationBar() {
return BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.business),
label: 'Business',
),
BottomNavigationBarItem(
icon: Icon(Icons.school),
label: 'School',
),
],
currentIndex: 0,
selectedItemColor: Colors.amber[800],
onTap: (v) {},
);
}
}
class SideWidget extends StatelessWidget {
const SideWidget({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Material(
child: Container(
width: 63,
color: Colors.white,
child: ListView(
children: [
...[
Icons.headset,
Icons.pets,
Icons.watch,
Icons.color_lens,
Icons.today
]
.map((e) => Padding(
padding: const EdgeInsets.symmetric(
vertical: 16.0, horizontal: 4.0),
child: TextButton(
onPressed: () {},
child: Icon(
e,
color: Colors.blueGrey,
size: 40,
),
),
))
.toList()
],
),
),
);
}
}
class ItemWidget extends StatelessWidget {
var data;
ItemWidget(this.data, {Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
height: 150,
child: Card(
child: Column(
children: [
Expanded(
child: Container(
height: 125,
child: GridTile(
// footer:Text(data["Name"]) ,
child: Image.network(
data["Image"],
alignment: Alignment.center,
fit: BoxFit.cover,
),
),
),
),
Center(
child: Text(
data["Name"],
style: TextStyle(fontSize: 12),
))
],
),
),
);
}
}
GridView children size depends on aspect ratio, which is 1 by default. In your case, image is not getting proper height.
For your case, You can use fit on Image.asset.
Image.asset(
"",
fit: BoxFit.cover, // or the .width or the one you prefer
),
Also you can try GridTile
GridTile(
child: Image.asset(
"",
fit: BoxFit.cover,
),
footer: Text("title"),
),
More about GridTile and BoxFit.
Firstly, the way you have created the widget tree is not proper.
Currently, you have
Card -> Container -> Column -> 1. Image
2. Text
If you want the title to be out of your square (Card), it should be:
Column -> 1. Card -> Image
2. Text
This way your title will be out of the card.

Flutter web: How to make horizontal scroll in stepper form?

I am trying to make a flutter web form using stepper and i am doing the experiment for small size screen. I have done the vertical scroll using the physics: ClampingScrollPhysics() method. However, I am unable to make horizontal scroll inside the stepper step. I want to make the radio button horizontally scroll able so that the error message will hide and i the text goes out of the screen, the user can scroll to that part. I already used SingleChildCcrollView(crollDirection: Axis.horizontal) but it didn't work. The image is
The code for the flutter program is as below: -
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Stepper Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Stepper Tutorial'),
);
}
}
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> {
int _currentStep = 0;
TextEditingController nameController = TextEditingController();
TextEditingController emailController = TextEditingController();
TextEditingController addressController = TextEditingController();
List<String> demoList = [];
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.start,
),
Expanded(
child: SingleChildScrollView(
// scrollDirection: Axis.horizontal,
child: Stepper(
physics: ClampingScrollPhysics(),
steps: _mySteps(),
currentStep: this._currentStep,
onStepTapped: (step) {
setState(
() {
this._currentStep = step;
},
);
},
onStepContinue: () {
setState(
() {
if (this._currentStep < this._mySteps().length - 1) {
this._currentStep = this._currentStep + 1;
}
},
);
},
onStepCancel: () {
setState(
() {
if (this._currentStep > 0) {
this._currentStep = this._currentStep - 1;
} else {
this._currentStep = 0;
}
},
);
},
),
),
),
demoList.isEmpty
? Text("")
: Column(
children: demoList.map((e) {
return Text(e);
}).toList(),
),
ElevatedButton(
onPressed: () {
demoList = [];
viewList();
},
child: Text("Click to see List"),
),
],
),
);
}
viewList() {
if (nameController.text.isEmpty ||
emailController.text.isEmpty ||
addressController.text.isEmpty) {
setState(
() {
if (nameController.text.isEmpty) {
demoList.add("Name field is empty");
} else if (emailController.text.isEmpty) {
demoList.add("Email field is Empty");
} else if (addressController.text.isEmpty) {
demoList.add("Address field is empty");
}
},
);
} else {
demoList.add(nameController.text);
demoList.add(emailController.text);
demoList.add(addressController.text);
setState(
() {
demoList = demoList;
},
);
}
}
List<Step> _mySteps() {
List<Step> _steps = [
Step(
title: Text('Name'),
content: TextField(
controller: nameController,
),
isActive: _currentStep >= 0,
),
Step(
title: Text('Email'),
content: TextField(
controller: emailController,
),
isActive: _currentStep >= 1,
),
Step(
title: Text('Address'),
content: TextField(
controller: addressController,
),
isActive: _currentStep >= 2,
),
Step(
title: Text('Number'),
content: Row(
children: <Widget>[
SingleChildScrollView(
physics: ClampingScrollPhysics(),
),
SafeArea(
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Form(
child: Row(
children: <Widget>[
Radio(
value: "1",
),
Text("1"),
Radio(
value: "2",
),
Text("2"),
Radio(
value: "3",
),
Text("3"),
Radio(
value: "4",
),
Text("4"),
Radio(
value: "5",
),
Text("5"),
Radio(
value: "6",
),
Text("6"),
Radio(
value: "7",
),
Text("7"),
Radio(
value: "8",
),
Text("8"),
Radio(
value: "9",
),
Text("9"),
],
),
),
),
)
],
),
isActive: _currentStep >= 2,
),
];
return _steps;
}
}
You can just use a ListView and set the scrollDirection to horizontal. The Container is there because it needs something to give it a size.
Step(
title: Text('Number'),
content: Container(
height: 100,
child: ListView(
scrollDirection: Axis.horizontal,
children: [
Radio(
value: "1",
),
Center(child: Text("1")),
Radio(
value: "2",
),
Center(child: Text("1")),
Radio(
value: "3",
),
Center(child: Text("3")),
Radio(
value: "4",
),
Center(child: Text("4")),
Radio(
value: "5",
),
Center(child: Text("5")),
Radio(
value: "6",
),
Center(child: Text("6")),
Radio(
value: "7",
),
Center(child: Text("7")),
Radio(
value: "8",
),
Center(child: Text("8")),
Radio(
value: "9",
),
Center(child: Text("9")),
],
),
),
isActive: _currentStep >= 2,
),

How can i rebuild a listview.builder?

I need to rebuild my listview because it is only maintaining the first build, unless I reset the app. I have a bottom sheet pop up that lets me select times and navigate me to a new page where the listview.builder builds. If I back out of the page, select new options, and go back into the page, it does not update. Here is an example:
Relevant Code:
final selectTimesTextStyle = TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
);
final List classBools = [
checkedPreBallet,
checkedBeginningBallet,
checkedIntermediateBallet,
checkedAdvancedBallet,
checkedJazz,
checkedPC,
];
final List<String> preballetItems = [
'Wednesday 3:00-4:00',
'Friday 3:00-3:35',
];
final List<String> privateClassesItems = [
'Mondays, Schedule Via Email',
];
final List<String> intermediateBalletItems = [
'Tuesday 5:00-6:00',
'Thursday 5:00-6:00',
'Saturday 10:00-11:00',
];
final List<String> advancedBalletItems = [
'Tuesday 6:00-7:00',
'Thursday 6:00-7:00',
];
final List<String> beginningBalletItems = [
'Wednesday 3:45-4:45',
'Friday 3:45-4:45',
];
final List<String> jazzItems = [
'Thursday 4:00-5:00',
];
final List<List> listOfLists = [
preballetItems,
beginningBalletItems,
intermediateBalletItems,
advancedBalletItems,
jazzItems,
privateClassesItems,
];
List<String> valueChoose = [
'Wednesday 3:00-4:00',
'Wednesday 3:45-4:45',
'Tuesday 5:00-6:00',
'Tuesday 6:00-7:00',
'Thursday 4:00-5:00',
'Mondays, Schedule Via Email',
];
class TimeSelection extends StatelessWidget {
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: InkWell(
onTap: () => {
Navigator.of(context).pop(),
currentIndex = 2,
checkedPreBallet = false,
checkedBeginningBallet = false,
checkedIntermediateBallet = false,
checkedAdvancedBallet = false,
checkedJazz = false,
checkedPC = false,
},
child: Container(
child: Icon(Icons.arrow_back),
),
),
title: Text('Select Times'),
centerTitle: true,
),
body: StatefulBuilder(
builder: (context, setState) => Column(
children: [
Expanded(
child: ListView.builder(
itemCount: 6,
itemBuilder: (context, index) => Visibility(
maintainState: false,
visible: classBools[index],
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
child: Text(
buttonTitles[index],
style: selectTimesTextStyle,
),
width: MediaQuery.of(context).size.width * 0.50,
),
Container(
width: MediaQuery.of(context).size.width * 0.40,
child: DropdownButton(
isExpanded: true,
underline: SizedBox(),
dropdownColor: Colors.white,
value: valueChoose[index],
onChanged: (newValue) => {
setState(() {
valueChoose[index] = newValue;
})
},
items: listOfLists[index]
.map((e) => DropdownMenuItem(
onTap: () => {
classBools[index] = true,
},
child: Text(e),
value: e,
))
.toList(),
),
),
],
),
),
),
),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 120,
vertical: 15,
),
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
stops: [
0.00005,
1,
],
colors: [
Theme.of(context).secondaryHeaderColor,
Theme.of(context).primaryColor,
]),
boxShadow: [
BoxShadow(color: Colors.black54, offset: Offset(3, 3)),
],
color: Colors.purpleAccent,
borderRadius: BorderRadius.circular(15),
),
child: InkWell(
onTap: () => {},
child: Padding(
padding: EdgeInsets.all(16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text('PayPal'),
],
),
),
),
),
),
],
),
),
);
}
}
bool checkedPreBallet = false;
bool checkedBeginningBallet = false;
bool checkedIntermediateBallet = false;
bool checkedAdvancedBallet = false;
bool checkedJazz = false;
bool checkedPC = false;
final List<String> buttonTitles = [
'Pre-Ballet',
'Beginning Ballet',
'Intermediate Ballet',
'Advanced Ballet',
'Jazz',
'Private Classes',
];
class RegisterPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Divider(),
Text('hello'),
Divider(),
RegisterCards(),
],
),
);
}
}
class RegisterCards extends StatefulWidget {
#override
_RegisterCardsState createState() => _RegisterCardsState();
}
class _RegisterCardsState extends State<RegisterCards> {
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: 30,
),
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
stops: [
0.00005,
1,
],
colors: [
Theme.of(context).secondaryHeaderColor,
Theme.of(context).primaryColor,
]),
boxShadow: [
BoxShadow(color: Colors.black54, offset: Offset(3, 3)),
],
color: Colors.purpleAccent,
borderRadius: BorderRadius.circular(15),
),
child: InkWell(
onTap: () => onButtonPressed(context),
child: Padding(
padding: EdgeInsets.all(16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text('Register Here'),
],
),
),
),
),
);
}
}
class ClassListWidget extends StatefulWidget {
#override
_ClassListWidgetState createState() => _ClassListWidgetState();
}
class _ClassListWidgetState extends State<ClassListWidget> {
#override
Widget build(BuildContext context) {
return StatefulBuilder(
builder: (context, setState) => Column(
children: [
CheckboxListTile(
value: checkedPreBallet,
onChanged: (value) => {
setState(() {
checkedPreBallet = value;
})
},
title: Text('Pre-Ballet'),
checkColor: Theme.of(context).scaffoldBackgroundColor,
activeColor: Theme.of(context).primaryColor,
secondary: Icon(PokemonIcons.i004_charmander),
controlAffinity: ListTileControlAffinity.leading,
tristate: false,
),
CheckboxListTile(
value: checkedBeginningBallet,
onChanged: (value) => {
setState(() {
checkedBeginningBallet = value;
})
},
title: Text('Beginning Ballet'),
checkColor: Theme.of(context).scaffoldBackgroundColor,
activeColor: Theme.of(context).primaryColor,
secondary: Icon(PokemonIcons.i004_charmander),
controlAffinity: ListTileControlAffinity.leading,
tristate: false,
),
CheckboxListTile(
value: checkedIntermediateBallet,
onChanged: (value) => {
setState(() {
checkedIntermediateBallet = value;
})
},
title: Text('Intermediate Ballet'),
checkColor: Theme.of(context).scaffoldBackgroundColor,
activeColor: Theme.of(context).primaryColor,
secondary: Icon(PokemonIcons.i004_charmander),
controlAffinity: ListTileControlAffinity.leading,
tristate: false,
),
CheckboxListTile(
value: checkedAdvancedBallet,
onChanged: (value) => {
setState(() {
checkedAdvancedBallet = value;
})
},
title: Text('Advanced Ballet'),
checkColor: Theme.of(context).scaffoldBackgroundColor,
activeColor: Theme.of(context).primaryColor,
secondary: Icon(PokemonIcons.i004_charmander),
controlAffinity: ListTileControlAffinity.leading,
tristate: false,
),
CheckboxListTile(
value: checkedJazz,
onChanged: (value) => {
setState(() {
checkedJazz = value;
})
},
title: Text('Jazz'),
checkColor: Theme.of(context).scaffoldBackgroundColor,
activeColor: Theme.of(context).primaryColor,
secondary: Icon(PokemonIcons.i004_charmander),
controlAffinity: ListTileControlAffinity.leading,
tristate: false,
),
CheckboxListTile(
value: checkedPC,
onChanged: (value) => {
setState(() {
checkedPC = value;
})
},
title: Text('Private Classes'),
checkColor: Theme.of(context).scaffoldBackgroundColor,
activeColor: Theme.of(context).primaryColor,
secondary: Icon(PokemonIcons.i004_charmander),
controlAffinity: ListTileControlAffinity.leading,
tristate: false,
),
],
),
);
}
}
void onButtonPressed(context) {
showModalBottomSheet(
isScrollControlled: false,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(15),
topRight: Radius.circular(15),
),
),
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
context: context,
builder: (context) => StatefulBuilder(
builder: (BuildContext context, setState) => Container(
child: Column(
children: [
ClassListWidget(),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 15,
),
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
stops: [
0.00005,
1,
],
colors: [
Theme.of(context).secondaryHeaderColor,
Theme.of(context).primaryColor,
]),
boxShadow: [
BoxShadow(color: Colors.black54, offset: Offset(3, 3)),
],
color: Colors.purpleAccent,
borderRadius: BorderRadius.circular(15),
),
child: InkWell(
onTap: () => {
Navigator.push(context, MaterialPageRoute(
builder: (context) => TimeSelection(),
)),
},
child: Padding(
padding: EdgeInsets.all(14),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text('Select Times'),
],
),
),
),
),
),
],
),
),
),
);
}
check this out whether it fits your need.
import 'package:flutter/material.dart';
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(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: TimeSelection(),
);
}
}
// model class for your ballet
class Ballet {
final String balletName;
final List<String> timeSchedules;
final String description;
String selectedTime;
bool isSelected = false;
Ballet({
this.balletName,
this.timeSchedules,
isSelected,
this.description = '',
this.selectedTime
}) {selectedTime ??= this.timeSchedules[0];}
}
List<Ballet> balletItems = <Ballet>[
Ballet(
balletName: "Pre-Ballet",
timeSchedules: [
'Wednesday 3:00-4:00',
'Friday 3:00-3:35',
],
),
Ballet(
balletName: "Private Classes",
timeSchedules: [
'Mondays',
],
description: 'Scheduled Via Email'
),
Ballet(
balletName: "Intermediate Ballet",
timeSchedules: [
'Tuesday 5:00-6:00',
'Thursday 5:00-6:00',
'Saturday 10:00-11:00',
],
),
Ballet(
balletName: "Advance Ballet",
timeSchedules: [
'Tuesday 6:00-7:00',
'Thursday 6:00-7:00',
],
),
Ballet(
balletName: "Beginning Ballet",
timeSchedules: [
'Wednesday 3:45-4:45',
'Friday 3:45-4:45',
],
),
Ballet(
balletName: "Jazz Ballet",
timeSchedules: [
'Thursday 4:00-5:00',
],
)
];
class TimeSelection extends StatefulWidget {
#override
_TimeSelectionState createState() => _TimeSelectionState();
}
class _TimeSelectionState extends State<TimeSelection> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Center(
child: Column(
children: [
Text('hello there', style: Theme.of(context).textTheme.headline4),
ElevatedButton(child: Text('Register Here',), onPressed: () {},),
],
),
),
Expanded(
child: ListView.builder(
itemCount: balletItems.length+1 ,
itemBuilder: (context, index){
if (index < balletItems.length) {
Ballet balletItem = balletItems[index];
return ListTile(leading: Checkbox(
value: balletItem.isSelected,
onChanged: (value) {
setState((){
balletItem.isSelected = value;
});
},),
title: Text(balletItem.balletName),
trailing: Icon(Icons.auto_awesome),
);}
else{
return Container(
margin: const EdgeInsets.symmetric(horizontal: 20.0),
child: ElevatedButton(
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(builder: (context) => SelectTimes(),));
},
child: Text('Select Times'),
),
);}
},
),
)
],
),
drawer: Drawer(),
appBar: AppBar(title: Text("Class Registration"),),
);
}
}
class SelectTimes extends StatefulWidget {
#override
_SelectTimesState createState() => _SelectTimesState();
}
class _SelectTimesState extends State<SelectTimes> {
List<Ballet> selectedBalletItems;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Select Times'),),
body: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
children: [
Expanded(
child: ListView.builder(
itemCount: selectedBalletItems.length,
itemBuilder: (context, index) {
Ballet selectedBalletItem = selectedBalletItems[index];
return _listTile(selectedBalletItem);
},
),
),
ElevatedButton(child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text("PayPal", style: Theme.of(context).textTheme.headline4,
),
),
onPressed: () {},)
],
),
)
);
}
Widget _listTile(Ballet selectedBalletItem) {
return ListTile(
title: Text(selectedBalletItem.balletName),
subtitle: Text(selectedBalletItem.description , style: Theme.of(context).textTheme.bodyText2.copyWith(color: Colors.grey[500])),
trailing: DropdownButton<String>(
value: selectedBalletItem.selectedTime,
items: selectedBalletItem.timeSchedules.map((timeSchedule) {
return DropdownMenuItem(value: timeSchedule, child: Text(timeSchedule));
} ).toList(),
onChanged: (value) {
setState(() {
selectedBalletItem.selectedTime = value;
});
},
)
);
}
#override
void initState() {
super.initState();
selectedBalletItems = balletItems.where((e) => e.isSelected).toList();
}
}

Categories

Resources