boolean expression must not be empty error in Flutter - flutter

I'm trying to check if the user likes the current post and set an icon. I'm trying to do a simple check but it throws an error.
The method I created
List<String> fav = List<String>();
checkFav(String id) {
bool isFav = fav.contains(id);
if(isFav)
return true;
else
return null;
}
And where I use the method
IconButton(
icon: Icon(favorite.checkFav(widget.blogModel.id)
? Icons.favorite
: Icons.favorite_border,
color: Colors.redAccent),
onPressed: () {
setState(
() {
favorite.checkFav(widget.blogModel.id)
? favorite.deleteItemToFav(widget.blogModel.id)
: favorite.addItemToFav(widget.blogModel.id);
},
);
//favorite.checkItemInFav(widget.blogModel.id, context);
},
),

Your checkFav should specify it returns bool. Also, you are returning null in case of false which is properly not what you have intended.
So you can rewrite your method to the following which will properly work:
bool checkFav(String id) => fav.contains(id);

Good day. Try this code:
class MyHomePage extends StatelessWidget {
final _favorites = <String>['1', '2', '3'];
#override
Widget build(BuildContext context) {
final buttonIsActive = checkFavorites('1', _favorites);
return Scaffold(
body: Center(
body: Center(child: buildFavoriteButton(isActive: buttonIsActive)),
),
);
}
}
bool checkFavorites(String id, List<String> favorites) {
return favorites.contains(id);
}
Widget buildFavoriteButton({bool isActive = false}) {
return IconButton(
icon: Icon(
Icons.ac_unit,
color: isActive ? Colors.red : Colors.grey,
),
onPressed: () {},
);
}

Related

flutter api returning data but its not workin in listviewbuilder

I'm tryig to solve an error in flutter list view builder once im calling my api functions its showing me the exact data i want, but when im giving the variable to listview builder it showing null value on that variable.
// import 'package:asanhisab/models/ledger_model.dart';
import 'package:asanhisab/utils/helper.dart';
import 'package:flutter/material.dart';
import 'package:odoo_api/odoo_api.dart';
import 'package:asanhisab/services/remoteservices.dart';
class GeneralLedgerScreen extends StatefulWidget {
const GeneralLedgerScreen({Key? key}) : super(key: key);
#override
State<GeneralLedgerScreen> createState() => _GeneralLedgerScreenState();
}
class _GeneralLedgerScreenState extends State<GeneralLedgerScreen> {
List? ledger;
bool isloaded = false;
#override
void initState() {
super.initState();
getLedgerData();
}
getLedgerData() async {
var ledger = await RemoteServices().getLedgerData();
if (ledger != null) {
setState(() {
isloaded = true;
});
}
logger.d(ledger.length);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('General Ledger'),
),
body: Scrollbar(
// child: Center(child: CircularProgressIndicator()),
child: Center(
child: Visibility(
visible: isloaded,
// ignore: sort_child_properties_last
child: ListView.builder(
itemCount: ledger?.length,
itemBuilder: (context, index) {
logger.d(ledger);
return Card(
child: ListTile(
leading: const Icon(Icons.payment),
title: Text(index.toString()),
subtitle: const Text('Name'),
iconColor: Colors.blue,
isThreeLine: true,
trailing: const Text('1000'),
onTap: () {},
),
);
},
),
replacement: const CircularProgressIndicator(),
),
),
),
floatingActionButton: FloatingActionButton.extended(
label: const Text('Create'),
icon: const Icon(Icons.add),
backgroundColor: Colors.blue,
onPressed: () {
// Get.to(() => const CreateAccountHead());
},
),
);
}
}
getLedgerData() async {
var client = OdooClient(storage.read('link'));
var authres = await client.authenticate(storage.read('email'),
storage.read('password'), storage.read('dbname'));
if (authres.isSuccess) {
var data = await client
.callKW('ah_general_ledger.ah_account_head', 'search_read', []);
if (data.getStatusCode() == 200) {
return data.getResult();
} else {
logger.d('Error Occured while fetching data');
// errorAlert(context, 'Error Occured while fetching data');
}
} else {
logger.d('Error Occured');
// errorAlert(context, 'Error Occured');
}
return null;
}
I'm tryig to solve an error in flutter list view builder once im calling my api functions its showing me the exact data i want, but when im giving the variable to listview builder it showing null value on that variable.
This is because your are redefined ledger in getLedgerData(), you should use your attribute instead.
getLedgerData() async {
ledger = await RemoteServices().getLedgerData(); // remove var here at the beginning
if (ledger != null) {
setState(() {
isloaded = true;
});
}
logger.d(ledger.length);
}
You can also use private field for your ledger and isloaded by adding _ caracter as prefix.

SpeedDial: change color on click

I'm trying to do so that if I click on a SpeedDialChild (button) then the color of it changes, but even if the value of fun.switchTakePhoto changes from true to false (and vice versa) the color remains red for some reason.
class MainPage extends StatefulWidget {
Home createState() => Home();
}
#immutable
class Home extends State<MainPage> {
//Home({super.key});
var fun = FunctionManager();
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ChangePWD()),
);
},
child: const Text('Change password'),
),
),
floatingActionButton: SpeedDial(
icon: Icons.settings,
backgroundColor: Colors.amber,
children: [
SpeedDialChild(
child: const Icon(Icons.photo_camera),
label: 'Activate/Deactivate: Take Photo',
backgroundColor: fun.switchSendPhoto == true
? const Color.fromARGB(255, 109, 255, 64)
: const Color.fromARGB(255, 255, 64, 64),
onTap: () {
setState(() {
fun.switchTakePhoto = !fun.switchTakePhoto;
});
},
),
]),
);
}
}
class FunctionManager {
bool switchTakePhoto = true;
bool switchSendPhoto = false;
bool switchRec = true;
bool switchPlay = true;
bool switchNotifications = true;
}
The issue might be with data class. I've solve this way.
class FunctionManager {
final bool switchSendPhoto;
FunctionManager({
this.switchSendPhoto = false,
});
FunctionManager copyWith({
bool? switchTakePhoto,
}) {
return FunctionManager(
switchSendPhoto: switchTakePhoto ?? switchSendPhoto,
);
}
}
A state-level variaable like
FunctionManager fun = FunctionManager()
And update data
onTap: () {
fun = fun.copyWith(switchTakePhoto: !fun.switchSendPhoto);
setState(() {});
},
Same goes for others

Change card color based on alertdialog option

I have a list of cards and each card has a long press function which when clicked, pops up an alert dialog. I would like the card to change color based on the option chosen in the alert dialog. My alert dialog has 3 options:
Completed (Card should change to color green),
In Progress ( Color orange),
Cancel (Color grey).
At first, when the screen loads, it should show list of cards each painted the color based on the value saved in the database. Then, when the user long presses a card and chooses an option from the alert dialog, the card's color should change based on the chosen option. Only that particular card's color should change.
I have read somewhere that this might be achievable using valuechangenotifier. So here's what I did so far:
First I created my changenotifier class like below:
import 'package:flutter/material.dart';
class ColorChanger with ChangeNotifier{
Color _color = Colors.white;
ColorChanger(this._color);
getColor() => _color;
setTheme (Color color) {
_color = color;
notifyListeners();
}
}
Then I used it in my dart class. However, the color does not seem to change. What am I missing here?
class OrderItem extends StatefulWidget {
final ord.OrderItem order;
OrderItem(this.order);
#override
_OrderItemState createState() => _OrderItemState();
}
class _OrderItemState extends State<OrderItem> {
var _expanded = false;
var mycolor = Colors.white;
#override
Widget build(BuildContext context) {
ColorChanger _color = Provider.of<ColorChanger>(context);
var listProducts = widget.order.products;
return Card(
color: widget.order.orderStatus=='completed'
?Colors.lightGreen:widget.order.orderStatus=='inprogress'?
Colors.orangeAccent:
widget.order.orderStatus=='cancelled'?Colors.grey:mycolor,
margin: EdgeInsets.all(10),
child: Column(
children: <Widget>[
ListTile(
title: RichText(
text: new TextSpan(
style: new TextStyle(
fontSize: 14.0,
color: Colors.black,
),
children: <TextSpan>[
new TextSpan(
text: 'Order Number : ',
style: new TextStyle(fontWeight: FontWeight.bold)),
new TextSpan(text: widget.order.uniqueOrderNumber),
],
),
),
trailing: IconButton(
icon: Icon(_expanded ? Icons.expand_less : Icons.expand_more),
onPressed: () {
setState(() {
_expanded = !_expanded;
});
},
),
onLongPress: toggleSelection,
),
],
),
);
}
void toggleSelection() {
ColorChanger _color = Provider.of<ColorChanger>(context,listen:false);
Widget completeOrder = FlatButton(
child: Text('Completed'),
onPressed: () async {
try {
Navigator.of(context).pop(true);
// setState(() {
_color.setTheme(Colors.lightGreen);
// });
await Provider.of<Orders>(context, listen: false)
.updateOrder(widget.order,'completed');
} catch (error) {
}
});
Widget startOrder = FlatButton(
child: Text('In progress'),
onPressed: () async {
try {
Navigator.of(context).pop(true);
// setState(() {
_color.setTheme(Colors.orangeAccent);
//});
//Update Db to mark order in progress
await Provider.of<Orders>(context, listen: false)
.updateOrder(widget.order,'inprogress');
} catch (error) {
}
});
Widget cancelOrder = FlatButton(
child: Text('Cancel'),
onPressed: () async {
try {
Navigator.of(context).pop(false);
// setState(() {
_color.setTheme(Colors.grey);
// });
//Update Db to mark order as cancelled
await Provider.of<Orders>(context, listen: false)
.updateOrder(widget.order,'cancelled');
} catch (error) {
}
});
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text('Take Action'),
content: Text('What do you want to do with the order?'),
actions: <Widget>[
startOrder,
completeOrder,
cancelOrder
],
),
);
});
}
}
SECOND TRY based on Loren's answer.
import 'package:flutter/material.dart';
class ColorChanger with ChangeNotifier{
Color color = Colors.white;
setTheme (Color newColor) {
color = newColor;
notifyListeners();
}
}
class OrderItem extends StatefulWidget {
final ord.OrderItem order;
OrderItem(this.order);
#override
_OrderItemState createState() => _OrderItemState();
}
class _OrderItemState extends State<OrderItem> {
var _expanded = false;
//Set the color based on what was last saved in the DB
void didChangeDependencies() async {
var colorChanger = Provider.of<ColorChanger>(context, listen: false);
if(widget.order.orderStatus=='completed')
colorChanger.setTheme(Colors.lightGreen);
else if(widget.order.orderStatus=='inprogress')
colorChanger.setTheme(Colors.orangeAccent);
else if(widget.order.orderStatus=='cancelled')
colorChanger.setTheme(Colors.grey);
super.didChangeDependencies();
}
#override
Widget build(BuildContext context) {
var listProducts = widget.order.products;
return Consumer<ColorChanger>(
builder: (context, colorChanger, child) {
return Card(
color: widget.order.orderStatus=='completed'
?Colors.lightGreen:widget.order.orderStatus=='inprogress'?
Colors.orangeAccent:
widget.order.orderStatus=='cancelled'?Colors.grey:mycolor,
margin: EdgeInsets.all(10),
child: Column(
children: <Widget>[
ListTile(
title: RichText(
text: new TextSpan(
style: new TextStyle(
fontSize: 14.0,
color: Colors.black,
),
children: <TextSpan>[
new TextSpan(
text: 'Order Number : ',
style: new TextStyle(fontWeight: FontWeight.bold)),
new TextSpan(text: widget.order.uniqueOrderNumber),
],
),
),
trailing: IconButton(
icon: Icon(_expanded ? Icons.expand_less : Icons.expand_more),
onPressed: () {
setState(() {
_expanded = !_expanded;
});
},
),
onLongPress: toggleSelection,
),
],
),
)};
}
void toggleSelection() {
ColorChanger _color = Provider.of<ColorChanger>(context,listen:false);
Widget completeOrder = FlatButton(
child: Text('Completed'),
onPressed: () async {
try {
Navigator.of(context).pop(true);
// setState(() {
_color.setTheme(Colors.lightGreen);
// });
await Provider.of<Orders>(context, listen: false)
.updateOrder(widget.order,'completed');
} catch (error) {
}
});
Widget startOrder = FlatButton(
child: Text('In progress'),
onPressed: () async {
try {
Navigator.of(context).pop(true);
// setState(() {
_color.setTheme(Colors.orangeAccent);
//});
//Update Db to mark order in progress
await Provider.of<Orders>(context, listen: false)
.updateOrder(widget.order,'inprogress');
} catch (error) {
}
});
Widget cancelOrder = FlatButton(
child: Text('Cancel'),
onPressed: () async {
try {
Navigator.of(context).pop(false);
// setState(() {
_color.setTheme(Colors.grey);
// });
//Update Db to mark order as cancelled
await Provider.of<Orders>(context, listen: false)
.updateOrder(widget.order,'cancelled');
} catch (error) {
}
});
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text('Take Action'),
content: Text('What do you want to do with the order?'),
actions: <Widget>[
startOrder,
completeOrder,
cancelOrder
],
),
);
});
}
}
When I do it this way, it changes the color of all the cards instead of just that one card. What am I doing wrong here?
Sharing order.dart
class OrderItem {
final String id;
final double amount;
final int deliveryFee;
final List<CartItem> products;
final DateTime dateTime;
final String deliveryMethod;
final String uniqueOrderNumber;
final String orderStatus;
final String userId;
final String customMessage;
final String customerName;
final String phoneNumber;
OrderItem(
{#required this.id,
#required this.amount,
#required this.products,
#required this.dateTime,
#required this.deliveryMethod,
#required this.uniqueOrderNumber,
#required this.isOrderComplete,
this.orderStatus,
#required this.customMessage,
#required this.deliveryFee,
this.customerName,
this.phoneNumber,
#required this.userId});
}
class Orders with ChangeNotifier {
final String authToken;
final String userId;
Orders(this.authToken, this.userId);
List<OrderItem> _orders = [];
List<OrderItem> get orders {
return [..._orders];
}
Future<void> updateOrder(OrderItem order,String orderStatus) async {
final id = order.id;
final customerId = order.userId;
final url =
'https://cv.firebaseio.com/orders/$customerId/$id.json?auth=$authToken';
try {
await http.patch(url,
body: json.encode({
'orderStatus':orderStatus
}));
} catch (error) {
print(error);
}
notifyListeners();
}
UPDATED ANSWER:
So when trying to do this with Provider I kept getting errors that would have required me to keep bugging you for more and more code to try and replicate everything you have going on, and I didn't want to get into that.
So this solution may or may not be acceptable to you because it uses GetX State Management, but it works. In addition it doesn't require wrapping your whole app in provider widgets so dealing with scope etc...is a non issue.
Let's add a statusColor property to your OrderItem model. This is what will get changed.
Color statusColor = Colors.white; // or whatever you you want the default color to be
Your updated Orders class that uses GetX instead of ChangeNotifier (again, not because Provider can't do this, but because I was dealing with too many errors and frankly GetX is easier in my opinion anyway)
class Orders extends GetxController {
final String authToken;
final String userId;
Orders(this.authToken, this.userId);
List<OrderItem> orders = []; // back to what I said earlier about no point in getters and setters here
// temp function just to test this on my end
void addOrder(OrderItem order) {
orders.add(order);
update();
}
// this loops through the list to find the matching order number,
// then updates the color for just that order
void updateOrderStatusColor({OrderItem updatedOrder, String status}) {
for (final order in orders) {
if (order.uniqueOrderNumber == updatedOrder.uniqueOrderNumber) {
switch (status) {
case 'completed':
{
order.statusColor = Colors.greenAccent;
}
break;
case 'inprogress':
{
order.statusColor = Colors.orangeAccent;
}
break;
case 'cancelled':
{
order.statusColor = Colors.grey;
}
break;
}
}
}
update(); // equivelent of notifyListeners();
}
// ...the rest of your class
}
A few small changes to your card. didChangeDependencies can go away entirely.
// it seems like you had 2 classes with the same name, which is not recommended
class OrderItemCard extends StatefulWidget {
final OrderItem order;
OrderItemCard(this.order);
#override
_OrderItemCardState createState() => _OrderItemCardState();
}
class _OrderItemCardState extends State<OrderItemCard> {
var _expanded = false;
final controller = Get.find<Orders>(); // equivilent of Provider.of... finds the same instance without needing context
void toggleSelection() {
Widget completeOrder = TextButton(
child: Text('Completed'),
onPressed: () async {
try {
Navigator.of(context).pop(true);
controller.updateOrderStatusColor(
updatedOrder: widget.order, status: 'completed'); // calling new function here
} catch (error) {}
});
Widget startOrder = FlatButton(
child: Text('In progress'),
onPressed: () async {
try {
Navigator.of(context).pop(true);
controller.updateOrderStatusColor(
updatedOrder: widget.order, status: 'inprogress');
} catch (error) {}
});
Widget cancelOrder = FlatButton(
child: Text('Cancel'),
onPressed: () async {
controller.updateOrderStatusColor(
updatedOrder: widget.order, status: 'cancelled');
try {
Navigator.of(context).pop(false);
} catch (error) {}
});
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text('Take Action'),
content: Text('What do you want to do with the order?'),
actions: <Widget>[startOrder, completeOrder, cancelOrder],
),
);
}
#override
Widget build(BuildContext context) {
return Card(
margin: EdgeInsets.all(10),
color: widget.order.statusColor, // new color property added to your model
child: Column(
children: <Widget>[
ListTile(
title: RichText(
text: new TextSpan(
style: new TextStyle(
fontSize: 14.0,
color: Colors.black,
),
children: <TextSpan>[
new TextSpan(
text: 'Order Number : ${widget.order.uniqueOrderNumber} ',
style: new TextStyle(fontWeight: FontWeight.bold)),
],
),
),
trailing: IconButton(
icon: Icon(_expanded ? Icons.expand_less : Icons.expand_more),
onPressed: () {
setState(() {
_expanded = !_expanded;
});
},
),
onLongPress: toggleSelection,
),
],
),
);
}
}
Not sure what you have going on in your UI but here's a quick demo of how it would work in GetX. It's a simple ListView.builder populated from the orders list from the GetX Class. The GetBuilder<Orders> widget rebuilds when update() is called. Also a simple button that adds a dummy item for demo purposes. I don't know how you're generating your unique order # but I'm just using the list index for this. Both inside a column within a scaffold on a demo page.
// Equivilent of Consumer but doesn't need context nor any provider widget above it
GetBuilder<Orders>(
builder: (controller) => Expanded(
child: ListView.builder(
itemCount: controller.orders.length,
itemBuilder: (context, index) =>
OrderItemCard(controller.orders[index])),
),
),
TextButton(
onPressed: () {
final controller = Get.find<Orders>();
final orderItem = OrderItem(
orderStatus: ' ',
uniqueOrderNumber: controller.orders.length
.toString(), // just a hack to generate a unique order # for demo
);
controller.addOrder(orderItem);
},
child: Text('Add Item'),
)
Last thing is just initializing the GetX Controller. It can be done anywhere as long as its before you try and use it.
void main() {
// initialing the GetX GetxController
// not sure how you're generating the required auth and user id
// but I'm just passing in empty strings for now
Get.put(Orders('', ''));
runApp(MyApp());
}
So if you're open to GetX here, you can leave Provider for any other ChangeNotifier classes you may have in place if you want. For this you would just need to replace any Consumer<Orders> with GetBuilder<Order> and then get rid of the Provider<Orders>(create:... widget entirely.
OLD ANSWER:
You're missing a couple things in order to be using Provider properly and get the color changing the way you want.
For starters, your Card needs to be wrapped in a Consumer widget that gets notified of changes and rebuilds its children. Inside the Consumer, you need to be using the color property of the ChangeNotifier class. It doesn't need to know or care about the orderStatus because you're already explicitly telling it to change color when you call the setTheme method.
Consumer<ColorChanger>( // this is what rebuilds and changes the color
builder: (context, colorChanger, child) {
return Card(
color: colorChanger.color, // colorChanger here is equivalent of declaring final colorChanger = Provider.of<ColorChanger>(context...
child: Column(
children: <Widget>[
ListTile(
title: RichText(
text: new TextSpan(
style: new TextStyle(
fontSize: 14.0,
color: Colors.black,
),
children: <TextSpan>[
new TextSpan(
text: 'Order Number : ',
style: new TextStyle(fontWeight: FontWeight.bold)),
new TextSpan(text: widget.order.uniqueOrderNumber),
],
),
),
trailing: IconButton(
icon: Icon(_expanded ? Icons.expand_less : Icons.expand_more),
onPressed: () {
setState(() {
_expanded = !_expanded;
});
},
),
onLongPress: toggleSelection,
),
],
),
);
});
Next, see this link as to why you're not gaining anything with using the private _color and public getColor in your ChangeNotifier class.
So lets simplify that a bit.
class ColorChanger with ChangeNotifier {
Color color = Colors.white;
ColorChanger(this.color);
setTheme(Color newColor) {
color = newColor;
notifyListeners();
}
}
Now, whenever you call the setTheme function from your dialog, that card will change to whatever color you pass into it because the Consumer widget is notified, and will rebuild with the updated color value of the ChangeNotifier class.
Something like this would be the simplest way to the thing you want to achieve:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
// define a list of colors:
final colors = <Color>[
Colors.white, // this is the inital color
Colors.green,
Colors.orange,
Colors.grey
];
int index = 0;
Future<int> showMyDialog(BuildContext context) async {
// Since all Navigator.push(...) and showDialog(...) calls are futures
// we can send values alongside them when we pop the context:
// final value = await Navigator.push(...);
// or
// final value = await showDialog(...);
// then we do a:
// Navigator.pop(context, SOME_VALUE,);
// the value variable will be assigned to the one we sent
return await showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('Take Action'),
content: Text('What do you want to do with the order?'),
actions: <Widget>[
TextButton(
child: Text('Completed',
style: TextStyle(
color: Colors.green,
)),
onPressed: () => Navigator.pop(context, 1)),
TextButton(
child: Text('In progress',
style: TextStyle(
color: Colors.orange,
)),
onPressed: () => Navigator.pop(context, 2)),
TextButton(
child: Text('Cancel',
style: TextStyle(
color: Colors.grey,
)),
onPressed: () => Navigator.pop(context, 3)),
],
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(children: <Widget>[
Card(
color: colors[index],
child: Container(width: 50, height: 50),
),
ElevatedButton(
child: Text('Show dialog'),
onPressed: () async {
// call the showMyDialog function, it returns
// a future int so we have to await it
final int _index = await showMyDialog(context);
// if the returned value (_index) is null we use
// the old one value to avoid erros in the code
setState(() => index = _index ?? index);
}),
]),
);
}
}
A very simple workaround would be to declare a global color variable cardColor and assign it to the color property of the card. Then on the alertdialog, change the 'onChange'or 'onTap' property of the widget so that on tapping, the widget changes the value of the global variable cardColor to a different color. Don't forget to do the final step i.e. changing the value of the variable, inside setState()
The best way to achieve it by using AwesomeDialog
https://pub.dev/packages/awesome_dialog
AwesomeDialog(
context: context,
dialogType: DialogType.INFO,
animType: AnimType.BOTTOMSLIDE,
title: 'Dialog Title',
desc: 'Dialog description here.............',
btnCancelOnPress: () {},
btnOkOnPress: () {},
)..show();

How to set state using button click in flutter?

I have a boolean isUserLoggedIn = false; in my main.dart file and when isUserLoggedIn = false i am loading
Widget build(BuildContext context) {
return Scaffold(
body: isUserLoggedIn == false ? IntroAuthScreen() : HomePage(),
);
This is working fine. IntroAuthScreen is loading. But there is a button in IntroAuthScreen i want the value of isUserLoggedIn to be true when user click the button and he will be redirected to HomePage() as above code show.
IntroAuthCode:-
child: ElevatedButton.icon(
icon: Icon(
Icons.navigate_next,
color: Colors.white,
),
onPressed: () {
setState(() {
username = usernameController.text;
isUserLoggedIn = true;
});
print(username);
Navigator.pop(context);
},
label: Text("Finish"),
),
but its not working. help me
What if you try to create a wrapper class rather than switching the content of the scaffold?
Perhaps something like this:
class AuthWrapper extends StatelessWidget {
#override
Widget build(BuildContext context) {
final _user = Provider.of<User>(context);
return (_user == null) ? IntroAuthScreen() : HomeScreen();
}
}
The answer does make use of Provider, but it's definitely a worthwhile package to consider learning.
Check Below code.
Widget build(BuildContext context) {
return Scaffold(
body: isUserLoggedIn == false ? IntroAuthScreen() : HomePage(),
);
IntroAuthScreen() async {
bool isLoggedIN = await Navigator.push(MaterialPageRoute Bla Bla);
setState((){
isUserLoggedIn = isLoggedIN ?? false;
});
}
}
In Auth Code
child: ElevatedButton.icon(
icon: Icon(
Icons.navigate_next,
color: Colors.white,
),
onPressed: () {
setState(() {
username = usernameController.text;
isUserLoggedIn = true;
});
print(username);
Navigator.pop(context, isUserLoggedIn);
},
label: Text("Finish"),
),

how to change icon color immediately after pressed in flutter?

I would like to change the color of an icon after pressing it, but it seems the following code doesn't work.
void actionClickRow(String key) {
Navigator.of(context).push(
new MaterialPageRoute(builder: (context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(key),
actions: <Widget>[
new IconButton(
icon: new Icon(
Icons.favorite,
color: isSaved(key) ? Colors.red : null, //<--- if key is already saved, then set it to red
),
onPressed: ()
{
setState(() //<--whenever icon is pressed, force redraw the widget
{
pressFavorite(key);
});
}
),
],
),
backgroundColor: Colors.teal,
body: _showContent(key));
}),
);
}
void pressFavorite(String key)
{
if (isSaved(key))
saved_.remove(key);
else
saved_.add(key);
}
bool isSaved(String key) {
return saved_.contains(key);
}
Currently, if I press the icon, its color will not change, I have to go back to its parent, then re-enter.
I am wondering how to change its color immediately, Thanks.
update:
class MainPage extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return new MainPageState();
}
}
class MainPageState extends State<MainPage> {
bool _alreadySaved;
void actionRowLevel2(String key) {
_alreadySaved = isSaved(key);
Navigator.of(context).push(
new MaterialPageRoute(builder: (context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(key),
actions: <Widget>[
new IconButton(
icon: new Icon(
_alreadySaved ? Icons.favorite : Icons.favorite_border,
color: _alreadySaved ? Colors.red : null,
),
onPressed: ()
{
setState(()
{
pressFavorite(key);
_alreadySaved = isSaved(key); //<--update alreadSaved
});
}
),
],
),
backgroundColor: Colors.teal,
body: _showScript(key));
}),
);
}
You can simply put a condition for each color :
color:(isPressed) ? Color(0xff007397)
: Color(0xff9A9A9A))
and in the onPressed function :
onPressed: ()
{
setState(()
{
isPressed= true;
});
}
You need to use setState() function. Wherever you are updating your variable values.
For example, I want to update my _newVar value to newValue and this should be updated into the view then instead of writing
_newVar = newValue;
it should be:
setState(() {
_newVar = newValue;
});