Related
i have implement a List from api and it gives me actual response which is working fine. but when i implemented a list search on it. Then the list doesn't show up when i open that screen. but when i start searching it gives me the correct search results.
here is my code:
import 'dart:convert';
import 'package:fb_installer_phase1/api/controller/user_auth_controller.dart';
import 'package:fb_installer_phase1/api/model/technician.dart';
import 'package:fb_installer_phase1/views/user_management/add_user_screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import '../../api/network_calls/api_configration.dart';
import '../../utils/app_constants.dart';
import '../../utils/color_resourse.dart';
class UserListScreen extends StatefulWidget {
const UserListScreen({Key? key}) : super(key: key);
#override
State<UserListScreen> createState() => _UserListScreenState();
}
class _UserListScreenState extends State<UserListScreen> {
final TextEditingController searchController = TextEditingController();
String keyword = '';
bool isDataLoading = false;
List<TechData> _technicians = <TechData>[];
List<TechData> _techniciansList = <TechData>[];
Future getData() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
bearerToken = preferences.getString(AppConstants.appToken)!;
String url = AppConstants.baseUrl + AppConstants.allTechnicianListApi;
try {
final response = await http.get(Uri.parse(url), headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $bearerToken',
});
debugPrint("Token: $bearerToken");
debugPrint("Response::: ${response.body}");
TechnicianModel model = TechnicianModel.fromJson(
jsonDecode(response.body));
_technicians = model.data!;
setState(() {
isDataLoading = false;
isDataLoading = !isDataLoading;
});
print("hello...: ${_technicians.length}");
} catch (exception) {
print(exception);
}
}
#override
void initState() {
getAllTechniciansData();
getData();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
backgroundColor: ColorResources.primaryColor,
child: Center(
child: Icon(
Icons.add,
size: 25.h,
),
),
onPressed: () {
Get.to(() => const AddUserScreen());
},
),
appBar: AppBar(
flexibleSpace: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.centerLeft,
end: Alignment.centerRight,
stops: [
0.2,
0.7,
1,
],
colors: [
Color(0XFF3DDA76),
Color(0XFF6DD2D1),
Color(0XFF41B1A1),
],
)),
),
centerTitle: true,
backgroundColor: ColorResources.primaryColor,
title: const Text("User List"),
systemOverlayStyle: SystemUiOverlayStyle.light,
),
body: Column(
children: [
SizedBox(
height: 20.h,
),
_createSearchbar(),
SizedBox(
height: 15.h,
),
Container(
width: double.infinity,
margin: EdgeInsets.symmetric(horizontal: 15.w),
height: 35.h,
color: const Color(0xffF2F2F2),
child: Row(
children: [
Container(
width: 80.w,
height: double.infinity,
color: Colors.transparent,
alignment: Alignment.centerLeft,
padding: EdgeInsets.only(left: 10.w),
child: Text(
"Name",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w600,
fontSize: 12.sp),
),
),
Container(
width: 170.w,
height: double.infinity,
color: Colors.transparent,
alignment: Alignment.centerLeft,
padding: EdgeInsets.only(left: 10.w),
child: Text(
"Email",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w600,
fontSize: 12.sp),
),
),
Container(
height: double.infinity,
color: Colors.transparent,
alignment: Alignment.centerLeft,
padding: EdgeInsets.only(left: 10.w),
child: Text(
"App Status",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w600,
fontSize: 12.sp),
),
)
],
),
),
_userListView(),
],
),
);
}
#override
void dispose() {
super.dispose();
FocusScope.of(context).unfocus();
}
Container _createSearchbar() {
return Container(
height: 50.h,
margin: EdgeInsets.symmetric(horizontal: 15.w),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.white,
border: Border.all(color: ColorResources.grey300)),
child: Row(
children: [
SizedBox(
height: 50.h,
width: 40.h,
child: const Center(
child: Icon(
Icons.search,
color: ColorResources.primaryColor,
),
),
),
Expanded(
child: TextField(
decoration: InputDecoration(
border: InputBorder.none,
focusedBorder: InputBorder.none,
enabledBorder: InputBorder.none,
errorBorder: InputBorder.none,
disabledBorder: InputBorder.none,
contentPadding:
EdgeInsets.only(left: 15.w, bottom: 11.h, top: 11, right: 15),
hintText: "Search here",
),
onChanged: searchTechnicians,
)),
],
),
);
}
TextEditingController controller = TextEditingController();
Widget _userListView() {
return isDataLoading || _techniciansList.isNotEmpty || controller.text.isNotEmpty
? Expanded(child: ListView.builder(
itemCount: _techniciansList.length ,
itemBuilder: (context, index) {
if (_techniciansList.isNotEmpty) {
return Container(
margin: EdgeInsets.symmetric(horizontal: 15.w),
height: 32.h,
//color: const Color(0xffF2F2F2),
child: Row(
children: [
Container(
width: 80.w,
height: double.infinity,
color: Colors.transparent,
alignment: Alignment.centerLeft,
padding: EdgeInsets.only(left: 10.w),
child: Text(
_techniciansList[index].name!,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w400,
overflow: TextOverflow.ellipsis,
fontSize: 11.sp),
),
),
Container(
width: 170.w,
height: double.infinity,
color: Colors.transparent,
alignment: Alignment.centerLeft,
padding: EdgeInsets.only(left: 10.w),
child: Text(
_techniciansList[index].email!,
overflow: TextOverflow.ellipsis,
maxLines: 2,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w400,
fontSize: 11.sp),
),
),
Expanded(
child: Container(
height: double.infinity,
color: Colors.transparent,
alignment: Alignment.centerLeft,
padding: EdgeInsets.only(left: 5.w),
child: Text(
_techniciansList[index].phone! ?? '',
style: TextStyle(
color: Colors.black,
overflow: TextOverflow.ellipsis,
fontWeight: FontWeight.w400,
fontSize: 11.sp),
),
),
)
],
),
);
} else {
return const SizedBox();
}
}
))
: const Expanded(
child: Center(child: CircularProgressIndicator(
color: ColorResources.primaryColor,)),
);
}
searchTechnicians(String text) {
_techniciansList.clear();
if (text.isEmpty) {
setState(() {
});
return;
}
_technicians.forEach((element) {
if (element.name!.contains(text)
|| element.email!.contains(text)
|| element.phone!.contains(text)) {
_techniciansList.add(element);
}
});
print("searchresults: ${_techniciansList.length}");
setState(() {
});
}
}
Because initially your _techniciansList.length will be zero and your list view is depend on _techniciansList.length.
If you want to show the list you have to manage conditions like
if controller.text.isEmpty than show ListView with all product list
You need check if search field is empty pass _technicians, like this:
Widget _userListView() {
return isDataLoading ||
_techniciansList.isNotEmpty ||
controller.text.isNotEmpty ||
_technicians.isNotEmpty
? Expanded(
child: ListView.builder(
itemCount: controller.text.isEmpty
? _technicians.length
: _techniciansList.length,
itemBuilder: (context, index) {
if (_techniciansList.isNotEmpty || _technicians.isNotEmpty) {
return Container(
margin: EdgeInsets.symmetric(horizontal: 15.w),
height: 32.h,
//color: const Color(0xffF2F2F2),
child: Row(
children: [
Container(
width: 80.w,
height: double.infinity,
color: Colors.transparent,
alignment: Alignment.centerLeft,
padding: EdgeInsets.only(left: 10.w),
child: Text(
controller.text.isEmpty
? _technicians[index].name!
: _techniciansList[index].name!,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w400,
overflow: TextOverflow.ellipsis,
fontSize: 11.sp),
),
),
Container(
width: 170.w,
height: double.infinity,
color: Colors.transparent,
alignment: Alignment.centerLeft,
padding: EdgeInsets.only(left: 10.w),
child: Text(
controller.text.isEmpty
? _technicians[index].email!
: _techniciansList[index].email!,
overflow: TextOverflow.ellipsis,
maxLines: 2,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w400,
fontSize: 11.sp),
),
),
Expanded(
child: Container(
height: double.infinity,
color: Colors.transparent,
alignment: Alignment.centerLeft,
padding: EdgeInsets.only(left: 5.w),
child: Text(
controller.text.isEmpty
? _technicians[index].phone! ?? ''
: _techniciansList[index].phone! ?? '',
style: TextStyle(
color: Colors.black,
overflow: TextOverflow.ellipsis,
fontWeight: FontWeight.w400,
fontSize: 11.sp),
),
),
)
],
),
);
} else {
return const SizedBox();
}
}))
: const Expanded(
child: Center(
child: CircularProgressIndicator(
color: ColorResources.primaryColor,
)),
);
}
How do I go about this
I want to add something like a greeting, say "Hi James" before the Sliders , something like this
https://i.postimg.cc/cJQb8Cyz/Screenshot-1664302329.png
I wanted the greeting to be there , not sure how to go about it.
My source code is looking thus
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class TransactionDetails {
String? avatar;
String? name;
String? date;
String? amount;
TransactionDetails({
this.avatar,
this.name,
this.date,
this.amount,
});
TransactionDetails.fromJson(Map<String, dynamic> json) {
avatar = json['avatar'];
name = json['name'];
date = json['date'];
amount = json['amount'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['avatar'] = avatar;
data['name'] = name;
data['date'] = date;
data['amount'] = amount;
return data;
}
}
Future<List<TransactionDetails>> fetchAlbum() async {
final response = await http.get(Uri.parse(
'https://brotherlike-navies.000webhostapp.com/people/people.php'));
if (response.statusCode == 200) {
final List result = json.decode(response.body);
return result.map((e) => TransactionDetails.fromJson(e)).toList();
} else {
throw Exception('Failed to load data');
}
}
class BaseScreen extends StatelessWidget {
const BaseScreen({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text(
"My Bank",
style: TextStyle(
fontFamily: "Poppins",
color: Colors.white,
fontWeight: FontWeight.bold),
),
leading: Padding(
padding: const EdgeInsets.all(8.0),
child: CircleAvatar(
backgroundImage:
NetworkImage('https://placeimg.com/640/480/people'),
),
),
actions: [
IconButton(
icon: Icon(Icons.notifications_active_outlined,
color: Colors.white, size: 27),
onPressed: () {})
],
),
body: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: double.infinity,
height: 150,
child: ListView(
scrollDirection: Axis.horizontal,
children: [
Container(
margin: const EdgeInsets.all(15),
width: 319,
height: 100,
decoration: BoxDecoration(
color: Colors.green,
borderRadius: BorderRadius.circular(16)),
alignment: Alignment.center,
child: const Text(
'\$5200.00',
style: TextStyle(
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.bold),
),
),
Container(
margin: const EdgeInsets.all(15),
width: 319,
height: 100,
decoration: BoxDecoration(
color: Colors.green,
borderRadius: BorderRadius.circular(16)),
alignment: Alignment.center,
child: const Text(
'\$1200.00',
style: TextStyle(
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.bold),
),
),
SizedBox(height: 24),
],
),
),
Padding(
padding: EdgeInsets.all(15),
child: Text(
"Recent Transactions",
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
color: Colors.green),
),
),
Center(
child: FutureBuilder<List<TransactionDetails>>(
future: fetchAlbum(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
return ListTile(
leading: CircleAvatar(
child: Image.network(
snapshot.data![index].avatar.toString()),
),
title:
Text(snapshot.data![index].name.toString()),
trailing: Text(
snapshot.data![index].amount.toString()),
subtitle:
Text(snapshot.data![index].date.toString()),
);
});
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return const CircularProgressIndicator();
}))
],
)));
}
}
How do i put the greeting before the Sliders? Help is needed.
Add Text widget for text and SizedBox for space. You can also use Padding widget around Text.
),
body: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: 20,
), //gap or use Padding widget
Text("Greatins"),
SizedBox(
height: 20,
), //gap
SizedBox(
height: 150,
with Padding widget
body: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(
top: 8,
bottom: 8,
),
child: Text("Greatins"),
),
SizedBox(
class BaseScreen extends StatelessWidget {
const BaseScreen({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Padding(
padding: EdgeInsets.only(top: 1, left: 1),
child: Text(
"My Bank",
style: TextStyle(
fontFamily: "Poppins",
color: Colors.white,
fontWeight: FontWeight.bold),
),
),
leading: Padding(
padding: const EdgeInsets.all(8.0),
child: CircleAvatar(
backgroundImage:
NetworkImage('https://placeimg.com/640/480/people'),
),
),
actions: [
IconButton(
icon: Icon(Icons.notifications_active_outlined,
color: Colors.white, size: 27),
onPressed: () {})
],
),
body: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(
top: 8,
bottom: 8,
),
child: Text("Greatins"),
),
SizedBox(
height: 150,
child: ListView(
scrollDirection: Axis.horizontal,
children: [
Container(
margin: const EdgeInsets.all(15),
width: 319,
height: 100,
decoration: BoxDecoration(
color: Colors.green,
borderRadius: BorderRadius.circular(16)),
alignment: Alignment.center,
child: const Text(
'\$5200.00',
style: TextStyle(
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.bold),
),
),
Container(
margin: const EdgeInsets.all(15),
width: 319,
height: 100,
decoration: BoxDecoration(
color: Colors.green,
borderRadius: BorderRadius.circular(16)),
alignment: Alignment.center,
child: const Text(
'\$1200.00',
style: TextStyle(
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.bold),
),
),
SizedBox(height: 24),
],
),
),
Padding(
padding: EdgeInsets.all(15),
child: Text(
"Recent Transactions",
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
color: Colors.green),
),
),
Center(
child: FutureBuilder<List<TransactionDetails>>(
future: fetchAlbum(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
return ListTile(
leading: CircleAvatar(
child: Image.network(
snapshot.data![index].avatar.toString()),
),
title:
Text(snapshot.data![index].name.toString()),
trailing: Text(
snapshot.data![index].amount.toString()),
subtitle:
Text(snapshot.data![index].date.toString()),
);
});
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return const CircularProgressIndicator();
}))
],
)));
}
}
I am trying to add a fixed buildHelpCard(context, alldata) above the scrollable list but whenever I try to add the buildHelpCard the list got disappeared and only the buildHelpCard is showing ... can you guys please suggest me how to fix this issues
**here is my code**
```
import 'package:flutter/material.dart';
import '../colors/constants.dart';
import 'package:get/get.dart';
import 'package:flutter_svg/flutter_svg.dart';
class duesDetails extends StatefulWidget {
var data;
var count;
duesDetails(this.data, this.count);
#override
_duesDetailsState createState() => _duesDetailsState();
}
class _duesDetailsState extends State<duesDetails> {
#override
Widget build(BuildContext context) {
var alldata = widget.data; // added all value to data for easy access
int count = widget.count;
return Scaffold(
appBar: buildAppBar(alldata),
body: Container(
decoration: BoxDecoration(
color: kPrimaryColor.withOpacity(0.03),
),
child: Center(
child: ListView.builder(
itemBuilder: (BuildContext context, int index) {
return Card(
child: Padding(
padding: const EdgeInsets.only(
top: 22, bottom: 22, left: 16, right: 16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
InkWell(
onTap: () {},
child: Text(
'${alldata[count]['pay list'][index]['discription']}',
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 22),
),
),
Text(
'Capital',
style: TextStyle(color: Colors.grey.shade500),
),
],
),
Container(
height: 30,
width: 50,
child: Image.asset('assets/facebook.png'),
)
],
),
),
);
},
itemCount: alldata[count]['pay count'] == null ? 0 : alldata[count]['pay count'],
),
),
),
);
}
AppBar buildAppBar(var data) {
return AppBar(
backgroundColor: kPrimaryColor.withOpacity(.05),
elevation: 0,
//title: Obx(() => Text('Randas ', style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold),),),
title: Text("${data[0]['name']} Pay Details", style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold),),
iconTheme: IconThemeData(
color: kPrimaryColor,
size: 28.0,
),
);
}
Container buildHelpCard(BuildContext context, var data) {
return Container(
height: 150,
width: double.infinity,
child: Stack(
alignment: Alignment.bottomLeft,
children: <Widget>[
Container(
padding: EdgeInsets.only(
// left side padding is 40% of total width
left: MediaQuery.of(context).size.width * .4,
top: 20,
right: 20,
),
height: 130,
width: double.infinity,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Color(0xFF60BE93),
Color(0xFF1B8D59),
],
),
borderRadius: BorderRadius.circular(20),
),
child: RichText(
text: TextSpan(
children: [
TextSpan(
text: "${data[5]["title"]}\n",
style: Theme.of(context)
.textTheme
.headline6
.copyWith(color: Colors.white),
),
TextSpan(
text: "${data[5]["dis"]}",
style: TextStyle(
color: Colors.white.withOpacity(0.7),
),
),
],
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(0.0, 0.0, 210.0, 20.0),
child: SvgPicture.asset("assets/svg/friends.svg"),
),
],
),
);
}
}
```
NOTE - I want to add buildHelpCard(context, alldata) function above the start of the card list... but when I try to do this the list got disappeared
Try this
child: Column(
children: [
buildHelpCard()
Expanded(child:
ListView.builder(
itemBuilder: (BuildContext context, int index) {
return Card(
child: Padding(
padding: const EdgeInsets.only(
top: 22, bottom: 22, left: 16, right: 16),
child:........
I want to make here Listing of cicrleavater, and in that cicleavter size issue width not getting more than 20 ! i want to make listing like instagram stories...and each tap i want show same pages but data differnt and current circle avater border need to show yello color....! how to do that i show you my screen size issue top whre cicleavter size issue i want make dyanamic listview and show on border when i tapped on it it
class FolderPageTabBAr extends StatefulWidget {
#override
_FolderPageTabBArState createState() => _FolderPageTabBArState();
}
class _FolderPageTabBArState extends State<FolderPageTabBAr> {
List<Widget> pages = [
CampaignFolder(),
ShelfScreen(),
CampaignFolder(),
ShelfScreen(),
];
double Redius = 40.0;
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: pages.length,
initialIndex: 0,
child: Scaffold(
body: Stack(
children: <Widget>[
TabBarView(
children: pages,
),
Container(
margin: EdgeInsets.only(top: 110,left: 1),
child: SizedBox(
height: 80,
width: 500,
child: TabBar(
tabs: [
Column(
children: <Widget>[
CircleAvatar(
backgroundImage: NetworkImage(Globals.PhotographerProf),
radius: 22,
),
Padding(
padding: const EdgeInsets.all(8.0),
child:Text(
'ALL',
overflow: TextOverflow.ellipsis,
style: new TextStyle(
fontSize: 12.0,
fontFamily: 'Roboto',
color: new Color(0xFF212121),
fontWeight: FontWeight.bold,
),
),
)
],
),
Column(
children: <Widget>[
CircleAvatar(
radius: 22,
backgroundImage: NetworkImage(Globals.PhotographerProf),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
Globals.Buisnessname,
overflow: TextOverflow.ellipsis,
style: new TextStyle(
fontSize: 11.0,
fontFamily: 'Roboto',
color: new Color(0xFF212121),
fontWeight: FontWeight.bold,
),
),
)
],
),
Column(
children: <Widget>[
CircleAvatar(
backgroundImage: NetworkImage(Globals.PhotographerProf),
radius: 22,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
"Family",
overflow: TextOverflow.ellipsis,
style: new TextStyle(
fontSize: 10.0,
fontFamily: 'Roboto',
color: new Color(0xFF212121),
fontWeight: FontWeight.bold,
),
),
)
],
),
Column(
children: <Widget>[
CircleAvatar(
backgroundImage: NetworkImage(Globals.PhotographerProf),
radius: 22,
),
Padding(
padding: const EdgeInsets.all(8.0),
child:Text(
"Album",
overflow: TextOverflow.ellipsis,
style: new TextStyle(
fontSize: 9.0,
fontFamily: 'Roboto',
color: new Color(0xFF212121),
fontWeight: FontWeight.bold,
),
),
)
],
),
],
unselectedLabelColor: Colors.orange,
labelColor: Colors.deepOrange,
indicatorColor: Colors.transparent,
),
)
),
],
),
),
);
}
}
To create multiple (dynamic) views that look similar use List View Builder
FULL Example:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class MyClass {
final String url;
final int id;
MyClass(this.url, this.id);
}
class Foo extends StatefulWidget {
#override
State<StatefulWidget> createState() => FooState();
}
class FooState extends State<Foo> {
int selectedIndex = 0;
List<MyClass> items = [
MyClass('https://picsum.photos/250?image=9', 1),
MyClass('https://picsum.photos/250?image=10', 5),
MyClass('https://picsum.photos/250?image=11', 33)
];
#override
Widget build(BuildContext context) {
print("build");
return Scaffold(
appBar: AppBar(),
body: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
height: 90,
child: ListView.builder(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: items.length,
itemBuilder: (context, index) {
return GestureDetector(
onTap: () {
setState(() {
selectedIndex = index;
});
},
child: getAvatarView(items[index], index == selectedIndex),
);
},
),
),
Text(
"here is my page for id ${items[selectedIndex].id}",
style: TextStyle(backgroundColor: Colors.black, color: Colors.red),
),
],
),
);
}
Widget getAvatarView(MyClass item, bool isSelected) {
return Container(
margin: isSelected ? const EdgeInsets.all(5.0) : null,
decoration: BoxDecoration(
border: isSelected ? Border.all(color: Colors.yellow) : null),
child: Column(
children: <Widget>[
CircleAvatar(
backgroundImage: NetworkImage(item.url),
radius: 22,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'ALL',
overflow: TextOverflow.ellipsis,
style: new TextStyle(
fontSize: 12.0,
fontFamily: 'Roboto',
color: new Color(0xFF212121),
fontWeight: FontWeight.bold,
),
),
)
],
),
);
}
}
To pass multiple attributes in an item (callback function, url for img,...) use a List of Custom classes.
I am new to flutter, and working on a shopping cart project. i don't know how exatly i am suppose to ask this question but, here is what i wanted.
I am trying to update my UI when the cart item and prices changes, which means to display sum amount of products from ListView (Stateful widget) to main OrderPage Stateful widget. I know about setState() method, but i think i should use some callback methods here, dont know exactly.
I have explained in short in Image - see below img
What i have done: when user modify cart products, I have saved the value (price/product/count) in to constant value , i calculate the value and save in constant value, and later use that const var in Main widget (Main Ui), which does update when i close and reopen the page, but could not able to update when button pressed (product +/-buttons)
What i want to do is,
Update my total value when +/- buttons are pressed.
Here is my full code:
class cartConstant{
static int packageCount;
static List<int> list;
}
class OrderPage extends StatefulWidget {
#override
_OrderPageState createState() => _OrderPageState();
}
class _OrderPageState extends State<OrderPage> {
int data = 3;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
automaticallyImplyLeading: true,
iconTheme: IconThemeData(
color: Colors.black54, //change your color here
),
backgroundColor: Colors.white,
elevation: 1,
title: Text("Your order Summery",style: TextStyle(color: Colors.black54),),
centerTitle: true,
),
body: Container(
child:
FutureBuilder(
builder: (context, snapshot){
// var datas = snapshot.data;
return
ListView.builder(
physics: ClampingScrollPhysics(),
shrinkWrap: true,
itemCount: data,
itemBuilder: (BuildContext context, int index){
// Cart cart = datas[index];
return CartListView();
},
padding: EdgeInsets.symmetric(horizontal: 10.0),
scrollDirection: Axis.vertical,
);
},
),
),
bottomNavigationBar: _buildTotalContainer(),
);
}
Widget _buildTotalContainer() {
return Container(
height: 220.0,
padding: EdgeInsets.only(
left: 10.0,
right: 10.0,
),
child: Column(
children: <Widget>[
SizedBox(
height: 10.0,
),
Padding(
padding: const EdgeInsets.only(top: 10),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Subtotal",
style: TextStyle(
color: Color(0xFF9BA7C6),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
Text(
cartConstant.packageCount.toString(),
style: TextStyle(
color: Color(0xFF6C6D6D),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
],
),
),
SizedBox(
height: 15,
),
Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Discount",
style: TextStyle(
color: Color(0xFF9BA7C6),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
Text(
"0.0",
style: TextStyle(
color: Color(0xFF6C6D6D),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
],
),
SizedBox(
height: 10.0,
),
Divider(
height: 2.0,
),
SizedBox(
height: 20.0,
),
Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Cart Total",
style: TextStyle(
color: Color(0xFF9BA7C6),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
Text(
cartConstant.packageCount.toString(),
style: TextStyle(
color: Color(0xFF6C6D6D),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
],
),
SizedBox(
height: 20.0,
),
GestureDetector(
onTap: () {
// Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) => SignInPage()));
},
child: Container(
height: 50.0,
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(35.0),
),
child: Center(
child: Text(
"Proceed To Checkout",
style: TextStyle(
color: Colors.white,
fontSize: 18.0,
fontWeight: FontWeight.bold,
),
),
),
),
),
SizedBox(
height: 20.0,
),
],
),
);
}
}
class CartListView extends StatefulWidget {
#override
_CartListViewState createState() => _CartListViewState();
}
class _CartListViewState extends State<CartListView> {
int _counter = 1;
int getPrice(int i,int priceC){
cartConstant.packageCount = i*priceC;
return cartConstant.packageCount;
}
#override
Widget build(BuildContext context) {
return Card(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 15.0, vertical: 15.0),
child: Row(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
decoration: BoxDecoration(
border: Border.all(color: Color(0xFFD3D3D3), width: 2.0),
borderRadius: BorderRadius.circular(10.0),
),
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: 10.0,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
InkWell(
onTap: (){
setState(() {
_counter++;
if (_counter > 20) {
_counter = 20;
}
});
},
child: Icon(Icons.add, color: Color(0xFFD3D3D3))),
Text(
"$_counter",
style: TextStyle(fontSize: 18.0, color: Colors.grey),
),
InkWell(
onTap:(){
setState(() {
_counter--;
if (_counter < 2) {
_counter = 1;
}
});
},
child: Icon(Icons.remove, color: Color(0xFFD3D3D3))),
],
),
),
),
SizedBox(
width: 20.0,
),
Container(
height: 70.0,
width: 70.0,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/food.jpg"),
fit: BoxFit.cover),
borderRadius: BorderRadius.circular(35.0),
boxShadow: [
BoxShadow(
color: Colors.black54,
blurRadius: 5.0,
offset: Offset(0.0, 2.0))
]),
),
SizedBox(
width: 20.0,
),
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Employee Package",
style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold),
),
SizedBox(height: 5.0),
SizedBox(height: 5.0),
Container(
height: 25.0,
width: 120.0,
child: ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
Row(
children: <Widget>[
Text("Price",
style: TextStyle(
color: Color(0xFFD3D3D3),
fontWeight: FontWeight.bold)),
SizedBox(
width: 5.0,
),
InkWell(
onTap: () {},
child: Text(
getPrice(_counter, 2000).toString(),
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.red,
),
),
),
SizedBox(
width: 10.0,
),
],
),
],
),
),
],
),
Spacer(),
GestureDetector(
onTap: () {
},
child: Icon(
Icons.cancel,
color: Colors.grey,
),
),
],
),
),
);
}
}
you can also check from my cart screen shot below:
You can copy paste run full code below
You can use callback refresh() and pass callback to CartListView
code snippet
class _OrderPageState extends State<OrderPage> {
int data = 3;
void refresh() {
setState(() {});
}
...
itemBuilder: (BuildContext context, int index) {
// Cart cart = datas[index];
return CartListView(refresh);
},
...
class CartListView extends StatefulWidget {
VoidCallback callback;
CartListView(this.callback);
...
InkWell(
onTap: () {
setState(() {
_counter++;
if (_counter > 20) {
_counter = 20;
}
});
widget.callback();
},
working demo
full code
import 'package:flutter/material.dart';
class cartConstant {
static int packageCount;
static List<int> list;
}
class OrderPage extends StatefulWidget {
#override
_OrderPageState createState() => _OrderPageState();
}
class _OrderPageState extends State<OrderPage> {
int data = 3;
void refresh() {
setState(() {});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
automaticallyImplyLeading: true,
iconTheme: IconThemeData(
color: Colors.black54, //change your color here
),
backgroundColor: Colors.white,
elevation: 1,
title: Text(
"Your order Summery",
style: TextStyle(color: Colors.black54),
),
centerTitle: true,
),
body: Container(
child: FutureBuilder(
builder: (context, snapshot) {
// var datas = snapshot.data;
return ListView.builder(
physics: ClampingScrollPhysics(),
shrinkWrap: true,
itemCount: data,
itemBuilder: (BuildContext context, int index) {
// Cart cart = datas[index];
return CartListView(refresh);
},
padding: EdgeInsets.symmetric(horizontal: 10.0),
scrollDirection: Axis.vertical,
);
},
),
),
bottomNavigationBar: _buildTotalContainer(),
);
}
Widget _buildTotalContainer() {
return Container(
height: 220.0,
padding: EdgeInsets.only(
left: 10.0,
right: 10.0,
),
child: Column(
children: <Widget>[
SizedBox(
height: 10.0,
),
Padding(
padding: const EdgeInsets.only(top: 10),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Subtotal",
style: TextStyle(
color: Color(0xFF9BA7C6),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
Text(
cartConstant.packageCount.toString(),
style: TextStyle(
color: Color(0xFF6C6D6D),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
],
),
),
SizedBox(
height: 15,
),
Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Discount",
style: TextStyle(
color: Color(0xFF9BA7C6),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
Text(
"0.0",
style: TextStyle(
color: Color(0xFF6C6D6D),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
],
),
SizedBox(
height: 10.0,
),
Divider(
height: 2.0,
),
SizedBox(
height: 20.0,
),
Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Cart Total",
style: TextStyle(
color: Color(0xFF9BA7C6),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
Text(
"8000",
style: TextStyle(
color: Color(0xFF6C6D6D),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
],
),
SizedBox(
height: 20.0,
),
GestureDetector(
onTap: () {
// Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) => SignInPage()));
},
child: Container(
height: 50.0,
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(35.0),
),
child: Center(
child: Text(
"Proceed To Checkout",
style: TextStyle(
color: Colors.white,
fontSize: 18.0,
fontWeight: FontWeight.bold,
),
),
),
),
),
SizedBox(
height: 20.0,
),
],
),
);
}
}
class CartListView extends StatefulWidget {
VoidCallback callback;
CartListView(this.callback);
#override
_CartListViewState createState() => _CartListViewState();
}
class _CartListViewState extends State<CartListView> {
int _counter = 1;
int getPrice(int i, int priceC) {
cartConstant.packageCount = i * priceC;
return cartConstant.packageCount;
}
#override
Widget build(BuildContext context) {
return Card(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 15.0, vertical: 15.0),
child: Row(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
decoration: BoxDecoration(
border: Border.all(color: Color(0xFFD3D3D3), width: 2.0),
borderRadius: BorderRadius.circular(10.0),
),
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: 10.0,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
InkWell(
onTap: () {
setState(() {
_counter++;
if (_counter > 20) {
_counter = 20;
}
});
widget.callback();
},
child: Icon(Icons.add, color: Color(0xFFD3D3D3))),
Text(
"$_counter",
style: TextStyle(fontSize: 18.0, color: Colors.grey),
),
InkWell(
onTap: () {
setState(() {
_counter--;
if (_counter < 2) {
_counter = 1;
}
});
widget.callback();
},
child: Icon(Icons.remove, color: Color(0xFFD3D3D3))),
],
),
),
),
SizedBox(
width: 20.0,
),
Container(
height: 70.0,
width: 70.0,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/food.jpg"),
fit: BoxFit.cover),
borderRadius: BorderRadius.circular(35.0),
boxShadow: [
BoxShadow(
color: Colors.black54,
blurRadius: 5.0,
offset: Offset(0.0, 2.0))
]),
),
SizedBox(
width: 20.0,
),
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Employee Package",
style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold),
),
SizedBox(height: 5.0),
SizedBox(height: 5.0),
Container(
height: 25.0,
width: 120.0,
child: ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
Row(
children: <Widget>[
Text("Price",
style: TextStyle(
color: Color(0xFFD3D3D3),
fontWeight: FontWeight.bold)),
SizedBox(
width: 5.0,
),
InkWell(
onTap: () {},
child: Text(
getPrice(_counter, 2000).toString(),
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.red,
),
),
),
SizedBox(
width: 10.0,
),
],
),
],
),
),
],
),
Spacer(),
GestureDetector(
onTap: () {},
child: Icon(
Icons.cancel,
color: Colors.grey,
),
),
],
),
),
);
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: OrderPage(),
);
}
}
When the button is tapped, you just need to update the Subtotal amount and cart total.
Step 1 : Replace the harcoded value by a variable. So, something like :
Row(
children: <Widget>[
Text(
"Subtotal",
style: ...
),
Text(
"$subTotal",
style: ....
),
],
),
Step 2 : Now, add a code to calcualte subTotal and cartTotal. You already have code which increments and decrements the variable _counter. You just need to tweak that part like :
setState( (){
_counter++;
// So, the quantity is increased. Just get the price of current item and add in the sub total.
subTotal += priceC;
cartTotal = subTotal - discount;
} );