I have a page where once i have response i need to display items
here is my code
It keeps on showing loader and futureBuilder never gets triggered
#override
void initState() {
super.initState();
helper.getString(TOKEN_ID).then((value) {
userResponseFuture = repos.getUserDetails(value);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
margin: EdgeInsets.all(10),
alignment: Alignment.center,
color: Colors.white,
child: FutureBuilder<UserResponse>(
future: userResponseFuture,
builder: (context, snapShot) {
if (snapShot.hasData) {
return Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
CircleAvatar(
radius: 50.0,
backgroundImage: NetworkImage(snapShot
.data.profilePictureURL ??
"https://cdn.mos.cms.futurecdn.net/5e7ehPZf5RT6Jt2H9cQP6k-1024-80.jpg.webp"),
backgroundColor: Colors.brown,
),
FlatButton(
child: Row(
children: [
Icon(Icons.edit),
Text("Edit profile Image"),
],
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
ProfilePicScreen()));
},
),
],
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
snapShot.data.firstName +
" " +
snapShot.data.lastName,
style: TextStyle(color: Colors.blue.shade900)),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(snapShot.data.email,
style: TextStyle(color: Colors.blue.shade900)),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(snapShot.data.phoneNo ?? "",
style: TextStyle(color: Colors.blue.shade900)),
)
],
);
} else {
return SizedBox(
height: 30.0,
width: 30.0,
child: CircularProgressIndicator(
strokeWidth: 2.0,
));
}
},
)),
);
}
}
You need to add setState after assign a value to userResponseFuture;
helper.getString(TOKEN_ID).then((value) {
userResponseFuture = repos.getUserDetails(value);
setState((){})
});
because it is being after build method and your widget can't call the right future function.
Related
I want to stack two bottom sheet each other in flutter as show in photo. The upper one is shown when in error state. In photo, it build with alert dialog. I want is with bottom sheet. How can I get it?
Edit:
Here is my code that I want to do. Lower bottom sheet is with pin field, autoComplete. autoComplete trigger StreamController, and then streamBuilder watch Error state and show dialog.
confirmPasswordModalBottomSheet(
BiometricAuthRegisterBloc biometricAuthRegBloc) {
showMaterialModalBottomSheet(
context: context,
builder: (BuildContext context) {
return StreamBuilder(
stream: biometricAuthRegBloc.biometricAuthRegisterStream,
builder: (context,AsyncSnapshot<ResponseObject>biometricAuthRegSnapShot) {
if (biometricAuthRegSnapShot.hasData) {
if (biometricAuthRegSnapShot.data!.messageState ==
MessageState.requestError) {
showModalBottomSheet(context: context, builder:
(BuildContext context){
return Container(
width: 200,height: 200,
child: Center(child: Text('Helllllllllo'),),);
});
}
}
return SizedBox(
width: 100,
height: 300,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(
height: margin30,
),
Text(CURRENT_PIN_TITLE),
SizedBox(
height: margin30,
),
Padding(
padding: const EdgeInsets.only(
left: margin60, right: margin60),
child: PinCodeField(
pinLength: 6,
onChange: () {},
onComplete: (value) {
biometricAuthRegBloc.biometricAuthRegister(
biometricType:_biometricAuthTypeForApi,
password: value);
},
),
),
SizedBox(
height: margin30,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal:
margin80),
child: AppButton(
onClick: () {},
label: CANCEL_BTN_LABEL,
),
),
Container(
padding: const EdgeInsets.all(8.0),
margin:
EdgeInsets.symmetric(vertical: 8.0,
horizontal: 30),
decoration: BoxDecoration(
color: Colors.grey,
border: Border.all(color: Colors.black),
),
child: const Text(
FINGER_PRINT_DIALOG,
textAlign: TextAlign.center,
),
)
],
),
);
});
},
);
}
When I do like that above, I get setState() or markNeedsBuild() called during build. Error and why? Sorry for my previous incomplete question.
I am bit confused with your question but stacking two bottomsheet is just easy. You just need to call the showModalBottomSheet whenever you want it shown to user. You can check out the following implementation:
class HomeScreen extends StatelessWidget {
const HomeScreen({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: ElevatedButton(
onPressed: () {
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) {
return Container(
height: 500,
color: Colors.amber,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const Text('Modal BottomSheet 1'),
ElevatedButton(
child: const Text('Show second modal 2'),
onPressed: () {
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) {
return Container(
height: 200,
color: Colors.redAccent,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const Text('Modal BottomSheet 2'),
ElevatedButton(
child: const Text('Close BottomSheet'),
onPressed: () => Navigator.pop(context),
),
],
),
),
);
},
);
},
),
],
),
),
);
},
);
},
child: Text('Show bottom sheet 1'),
),
);
}
}
I have solution. All I need to do is, need to add WidgetBinding.insatance.addPostFrameCallback((timeStamp){showModalBottomSheet()}); in the StreamBuilder return.
starting my carrer in flutter development for 2 months
while doing this project based in flutter,i get data from rest api with bloc state management & listed it with listvieww builder, but want add sort & filter functionality to it,, can you please explain how to do with an example, excepting valuable suggestions from you guys
search and filter functionilty
class Upcoming extends StatefulWidget {
Upcoming({Key? key}) : super(key: key);
#override
State<Upcoming> createState() => _UpcomingState();
}
class _UpcomingState extends State<Upcoming> {
#override
Widget build(BuildContext context) {
return BlocBuilder<MOdelBloc, MOdelState>(
builder: (context, state) {
if (state is MOdelInitial) {
context.read<MOdelBloc>().add(LoadEVENT());
return const Center(
child: CircularProgressIndicator(),
);
} else if (state is ModelLoading) {
return const Center(
child: CircularProgressIndicator(),
);
} else if (state is ModelLoadedstate) {
return buildupcoming(state.fakestore);
} else if (state is ErrorSatte) {
return const Center(
child: Text('errorstate'),
);
}
return const Center(child: Text('error'));
},
);
}
}
Widget buildupcoming(List<CryptoCurrency> currency) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.yellow.shade400,
leading: const Icon(
Icons.portrait_rounded,
),
title: const Center(
child: Text(
'Upcoming Matches',
style: TextStyle(fontWeight: FontWeight.bold),
),
),
actions: const [
Icon(
Icons.headset,
),
SizedBox(
width: 5,
),
Icon(Icons.message)
],
),
body: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Container(
height: double.maxFinite,
margin: const EdgeInsets.all(10),
child:
Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {}, child: const Text('CRICKET')),
const SizedBox(
width: 15,
),
ElevatedButton(
onPressed: () {},
child: const Icon(Icons.sports_football))
],
),
const SizedBox(
height: 10,
),
Row(
children: const [
TextWidget(text: 'My Rooms', size: 20),
Spacer(),
Text(
'View all',
style: TextStyle(color: Colors.black45),
)
],
),
const SizedBox(
height: 5,
),
Container(
height: 170,
child: PageView.builder(
scrollDirection: Axis.horizontal,
itemCount: 3,
itemBuilder: (context, index) {
return Container(
margin: const EdgeInsets.only(left: 5),
child: Column(children: [
SliderCARD(
text1: currency[2].fullname.toString(),
text2: currency[3].fullname,
minitext1: currency[2].price.toString(),
minitext2: currency[4].price.toString(),
color: Colors.indigo,
height: 100,
),
Row(children: [IconButton(onPressed: ( ){},
icon: Icon(Icons.arrow_back)),IconButton(onPressed: (){}, icon: Icon(Icons.arrow_back_outlined))],)]));
})),
ListView.builder(
physics:const NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: currency.length,
itemBuilder: (context, index) {
final CryptoCurrency cryptoCurrency = currency[index];
return Container(
margin: const EdgeInsets.only(bottom: 10),
height: 100,
child: SliderCARD(
text1: cryptoCurrency.fullname,
text2: currency[3].fullname,
minitext1: cryptoCurrency.price.toString(),
minitext2: currency[4].price.toString(),
color: Colors.white,
height: 100,
));
})
])),
));
}
I am trying to make a list view only occupy part of the screen, but it keeps growing till the end not respecting the contianer constraints. I tried to use a sizedbox too but it didn' work. List tiles outside the container are shown without any widget inside, but the background is shown anyways
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: pedidos,
builder: (context, AsyncSnapshot<List<Pedido>> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
SizedBox(
height: MediaQuery.of(context).size.height * 0.6,
child: ListView.builder(
itemCount: snapshot.data!.length,
shrinkWrap: true,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Hero(
tag:
"pedidos_card${snapshot.data![index].idPedido}",
child: ListTile(
tileColor: Colors.white,
leading: Container(
width: 50,
height: 50,
decoration: BoxDecoration(
color: Colors.blue,
shape: BoxShape.circle),
child: Center(
child: Text(
style: Theme.of(context)
.textTheme
.headlineSmall,
"${snapshot.data![index].idPedido}"),
),
),
title: Text(
'Pedido: ${snapshot.data![index].idPedido}'),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(height: 10),
Text(
'Estado: ${snapshot.data![index].estadoPedido.last.tipoEstadoPedido.name}'),
SizedBox(height: 10),
Text(
"Cliente: ${snapshot.data![index].cliente.nombre}")
],
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
trailing: Checkbox(
value: pedidosSeleccion
.contains(snapshot.data![index]),
onChanged: (bool? value) {
// value = checkboxList[index];
// setState(() {});
},
),
onTap: () {
bool isSelected = pedidosSeleccion
.contains(snapshot.data![index]);
if (isSelected) {
pedidosSeleccion
.remove(snapshot.data![index]);
} else {
pedidosSeleccion.add(snapshot.data![index]);
}
setState(() {});
},
),
));
}),
),
ElevatedButton(
onPressed: () {}, child: Text('Ver ultima milla')),
],
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
});
}
}
example
you can use Expanded instead of Sizedbox
eg:-
Column(
children:[
Expanded(flex:9,
child: ListView(
padding: const EdgeInsets.only(top: 10.0),
children: snapshot.map((data) => _buildListItem(context, data)).toList(),
),
),
Expanded(flex:1,
child:
ElevatedButton(
// fill in required params
),
)
])
I am using firestore and created 4 cards on which the user taps on goes to the next screen. Everything is working fine in debug mode, in debug mode both Inkwell and Gesture Detector are working but when I make a release version I don't know why but both Inkwell and Gesture Detector are not working. Have no idea what's causing this. Please help.
class _RestaurantDashboardState extends State<RestaurantDashboard> {
Widget buildRestaurantCards(String title, IconData iconData, int orderCount) {
return Expanded(
child: GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () {
if (title == "Menu\nManagement") {
Navigator.push(context,
MaterialPageRoute(builder: (context) => MenuManagement()));
} else if (title == "Current Orders") {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => OrderScreen("In Progress"),
),
);
} else if (title == "Order History") {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => OrderHistory("In Progress"),
),
);
} else if (title == "Update Profile") {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
RestaurantSignUp(Utils.restaurant!.restaurantId, true),
),
);
}
},
child: Container(
height: double.infinity,
child: Card(
margin: EdgeInsets.all(8),
elevation: 8,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
margin: EdgeInsets.only(top: 16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
orderCount > 0
? Row(
children: [
Container(
alignment: Alignment.center,
width: 30,
height: 30,
margin: EdgeInsets.all(4),
padding: EdgeInsets.all(4),
child: FittedBox(
child: Text(
orderCount.toString(),
style: TextStyle(
color: Colors.white, fontSize: 18),
)),
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(16),
),
)
],
)
: SizedBox(),
Container(
margin: EdgeInsets.symmetric(horizontal: 16),
alignment: Alignment.centerRight,
child: Icon(
iconData,
size: 40,
),
),
],
),
),
Container(
width: double.infinity,
margin:
EdgeInsets.symmetric(horizontal: 16, vertical: 16),
alignment: Alignment.center,
child: FittedBox(
child: Text(
title,
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.w600),
textAlign: TextAlign.center,
),
)),
],
)),
),
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Dashboard'),
),
body: Container(
child: Column(
children: [
Container(
height: MediaQuery.of(context).size.height * 0.25,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
isFirebaseInitialized
? StreamBuilder(
stream: FirebaseFirestore.instance
.collection("orders")
.snapshots(),
builder: (context,
AsyncSnapshot<
QuerySnapshot<Map<String, dynamic>>>
snapshot) {
if (!snapshot.hasData) {
setState(() {
_isLoading = false;
});
return Container();
}
if (snapshot.hasError) {
setState(() {
_isLoading = false;
});
}
List<DocumentSnapshot> itemsList = [];
for (DocumentSnapshot doc
in snapshot.data!.docs) {
if (doc['restaurantId'] ==
Utils.restaurant!.restaurantId &&
doc['orderStatus'] == "In Progress") {
itemsList.add(doc);
}
}
return buildRestaurantCards("Current Orders",
Icons.list_alt, itemsList.length);
},
)
: buildRestaurantCards(
"Current Orders", Icons.list_alt, 0),
buildRestaurantCards("Order History", Icons.history, 0),
],
),
),
Container(
height: MediaQuery.of(context).size.height * 0.25,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
buildRestaurantCards(
"Menu\nManagement", Icons.restaurant_menu_rounded, 0),
buildRestaurantCards("Update Profile", Icons.person, 0),
],
),
),
],
),
)
);
}
}
Check if there are any exceptions caught in the debug console, If there are then fix those, then the issue will be resolved
I would like to change all app language without reload app. I used flutter_i18n
I have a switch language button on appBar and AppHomeScreen in body, here is build function in MyHomePage class:
addClickFn(model) {
FocusScope.of(context).requestFocus(FocusNode());
Navigator.push<dynamic>(
context,
MaterialPageRoute<dynamic>(
builder: (BuildContext context) => MyPopupScreen(callback: (c, id) => { }),
fullscreenDialog: true),
);
}
#override
Widget build(BuildContext context) {
return ScopedModelDescendant<ResponseDataModel>(
builder: (context, _, model) => Scaffold(
backgroundColor: AppTheme.white,
body: FutureBuilder<bool>(
future: getData(),
builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
if (!snapshot.hasData) {
return const SizedBox();
} else {
return Padding(
padding: EdgeInsets.only(
top: MediaQuery.of(context).padding.top),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
appBar(),
Expanded(
child: FutureBuilder<bool>(
future: getData(),
builder: (BuildContext context,
AsyncSnapshot<bool> snapshot) {
if (!snapshot.hasData) {
return const SizedBox();
} else {
return AppHomeScreen(
addClickFn: () => addClickFn(model));
}
},
),
),
],
),
);
}
},
),
));
}
appBar with onTap switch button function:
Widget appBar() {
return SizedBox(
height: AppBar().preferredSize.height,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 8, left: 8),
child: Container(
width: AppBar().preferredSize.height - 8,
height: AppBar().preferredSize.height - 8,
),
),
Expanded(
child: Center(
child: Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(
FlutterI18n.translate(context, "title"),
style: TextStyle(
fontSize: 22,
color: AppTheme.darkText,
fontWeight: FontWeight.w700,
),
),
),
),
),
Padding(
padding: const EdgeInsets.only(top: 8, right: 8),
child: Container(
width: AppBar().preferredSize.height - 8,
height: AppBar().preferredSize.height - 8,
color: Colors.white,
child: Material(
color: Colors.transparent,
child: InkWell(
borderRadius:
BorderRadius.circular(AppBar().preferredSize.height),
child: Image.asset(
'icons/flags/png/' + currentLang.languageCode + '.png',
package: 'country_icons'),
onTap: () async {
setState(() {
currentLang = currentLang.languageCode == 'vn'
? new Locale('gb')
: new Locale('vn');
});
await FlutterI18n.refresh(context, currentLang);
},
),
),
),
),
],
),
);
}
In AppHomePage I included BottomBarView with DashboardScreen as tab body
#override
Widget build(BuildContext context) {
return Container(
color: AppTheme.background,
child: Scaffold(
backgroundColor: Colors.transparent,
body: FutureBuilder<bool>(
future: getData(),
builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
if (!snapshot.hasData) {
return const SizedBox();
} else {
return Stack(
children: <Widget>[
tabBody,
bottomBar(),
],
);
}
},
),
),
);
}
Future<bool> getData() async {
await Future<dynamic>.delayed(const Duration(milliseconds: 200));
return true;
}
Widget bottomBar() {
return Column(
children: <Widget>[
const Expanded(
child: SizedBox(),
),
BottomBarView(
tabIconsList: tabIconsList,
addClick: () {
if (widget.addClickFn != null) widget.addClickFn();
},
changeIndex: (int index) {
if (index == 0) {
animationController.reverse().then<dynamic>((data) {
if (!mounted) {
return;
}
setState(() {
tabBody =
DashboardScreen(animationController: animationController);
});
});
}
},
),
],
);
}
And in DashboardScreen I show a label:
#override
Widget build(BuildContext context) {
return Container(
color: AppTheme.background,
child: Scaffold(
backgroundColor: Colors.transparent,
body: Stack(
children: <Widget>[
getMainListViewUI(),
// getAppBarUI(),
SizedBox(
height: MediaQuery.of(context).padding.bottom,
)
],
),
),
);
}
Widget getMainListViewUI() {
return ListView(
scrollDirection: Axis.vertical,
semanticChildCount: 10,
children: <Widget>[
Container(
padding:
EdgeInsets.only(top: 0.0, left: 24, right: 24, bottom: 24.0),
child: Text(FlutterI18n.translate(context, "label.welcome"),
textAlign: TextAlign.left,
style: TextStyle(
fontFamily: AppTheme.fontName,
fontWeight: FontWeight.w700,
fontSize: 30 + 6 - 6 * topBarOpacity,
letterSpacing: 1.2,
color: AppTheme.darkerText,
))),
],
);
}
When I click switch language button, all text in current context (title) translates very well, but in DashboardScreen (label.welcome) are not.
And when I click add button on bottomBar to redirect to MyPopupScreen then close this popup, text in DashboardScreen has been translated.
How can I change all text in DashboardScreen when click switch language button on MyHomePage?
Sorry for my bad english!!!
You call FlutterI18n.refresh with the old currentLang value.
Try this:
setState(() {
currentLang = currentLang.languageCode == 'vn'
? new Locale('gb')
: new Locale('vn');
FlutterI18n.refresh(context, currentLang);
});