Flutter Progress_state_button - how to change button state - flutter

I am trying to use the progress state button in flutter. From the pub.dev docs, the widget should be set up as follows
Widget buildTextWithIcon() {
return ProgressButton.icon(iconedButtons: {
ButtonState.idle: IconedButton(
text: "Send",
icon: Icon(Icons.send, color: Colors.white),
color: Colors.deepPurple.shade500),
ButtonState.loading:
IconedButton(text: "Loading", color: Colors.deepPurple.shade700),
ButtonState.fail: IconedButton(
text: "Failed",
icon: Icon(Icons.cancel, color: Colors.white),
color: Colors.red.shade300),
ButtonState.success: IconedButton(
text: "Success",
icon: Icon(
Icons.check_circle,
color: Colors.white,
),
color: Colors.green.shade400)
}, onPressed: onPressedIconWithText, state: stateTextWithIcon);
}
I have a function (already written and working fine) that I want to run when the button is clicked, changing the button state to ButtonState.loading then to ButtonState.success then back to ButtonState.idle. See below the function stated on the pub.dev site.
void onPressedIconWithText() {
switch (stateTextWithIcon) {
case ButtonState.idle:
stateTextWithIcon = ButtonState.loading;
Future.delayed(Duration(seconds: 1), () {
setState(() {
stateTextWithIcon = Random.secure().nextBool()
? ButtonState.success
: ButtonState.fail;
});
});
break;
case ButtonState.loading:
break;
case ButtonState.success:
stateTextWithIcon = ButtonState.idle;
break;
case ButtonState.fail:
stateTextWithIcon = ButtonState.idle;
break;
}
setState(() {
stateTextWithIcon = stateTextWithIcon;
});
}
}
However, I am new to coding, and have no idea at all on how to use "breaks" or to change the button state. Could anybody help with advising on how i would insert my funcion (let's say its just void runFunction() in to the above code, changing the state from idle --> loading (onPressed) --> success --. idle.
Any help would be greatly appreciated

You could use setState to update the values for stateTextWithIcon
ButtonState stateTextWithIcon = ButtonState.idle;
Widget buildTextWithIcon() {
return ProgressButton.icon(iconedButtons: {
ButtonState.idle: IconedButton(
text: "Send",
icon: Icon(Icons.send, color: Colors.white),
color: Colors.deepPurple.shade500),
ButtonState.loading:
IconedButton(text: "Loading", color: Colors.deepPurple.shade700),
ButtonState.fail: IconedButton(
text: "Failed",
icon: Icon(Icons.cancel, color: Colors.white),
color: Colors.red.shade300),
ButtonState.success: IconedButton(
text: "Success",
icon: Icon(
Icons.check_circle,
color: Colors.white,
),
color: Colors.green.shade400)
}, onPressed: (){
progressButton()
},
state: stateTextWithIcon,
);
this is the fucntion handled by my onPressed
Future progressButton() async {
setState(() {
//sets the state of stateTextWithIcon to loading once button is pressed
stateTextWithIcon = ButtonState.loading;
});
var url = 'https://google.com';
final response = await http.get(url);
if (response.statusCode == 200 || response.statusCode == 201) {
setState(() {
//sets the state of stateTextWithIcon to success if whatever request made was successful
stateTextWithIcon= ButtonState.success;
});
} else {
setState(() {
//sets the state of stateTextWithIcon to fail if the request was unsuccessful
stateTextWithIcon = ButtonState.fail;
});
}
}

Related

How to Send data as JSON over to MQTT broker in flutter

return RaisedButton(
color: Colors.green,
disabledColor: Colors.grey,
textColor: Colors.white,
disabledTextColor:Colors.black38 ,
child: Text("Break"),
onPressed: state == MQTTAppConnectionState.connectedSubscribed
? () {
setState(() {
value = 0;
action = jsonData;
});
publishMessage(action);
}
: null, //
);
}
I have multiple buttons in my app that passes different message to mqtt client
I want to pass different json data to mqtt client for each button
sample json data for single button
{
"Motor":"BLDC motor",
"Acc": 70,
"F/R": "Forward",
"Break":"False",
"Key":"True"
}
help me to pass single json data to mqtt client when the button is pressed
Pass the values in the publish method and make this changes there it will work
return RaisedButton(
color: Colors.green,
disabledColor: Colors.grey,
textColor: Colors.white,
disabledTextColor:Colors.black38 ,
child: Text("Break"),
onPressed: state == MQTTAppConnectionState.connectedSubscribed
? () {
setState(() {
break1 = "True";
value = 0;
});
publish(break1);
}
: null,//
);
void publish(String break1) {
final MqttClientPayloadBuilder builder = MqttClientPayloadBuilder();
builder.addString(
json.encode(
{
"break": "$break1",
}
)
);
_client!.publishMessage(_topic, MqttQos.exactlyOnce, builder.payload!);}

Flutter Button statemanagement using provider

In my flutter application I have a button for follow and unfollow a user.
buttonstate.isSelected && widget.user!.isFollowing == true
? ElevatedButton(
onPressed: () async {
await unfollowuser(widget.user!.id); //Api Call
},
child: Text(
'Following',
style: TextStyle(
color: Theme.of(context).disabledColor,
),
),
)
: ElevevatedButton(
onPressed: () async {
buttonstate.setButtonState(true);
await followuser(widget.user!.id); //Api Call
},
child: Text(
'Follow',
style: TextStyle(
color: Theme.of(context).accentColor,
),
),
),
My objective is whenever the button is pressed I want the Api call to happen as well as the state of the button should change from 'Follow' to 'Following'. Now the Api gets called, but the button wont change to 'following'. After the page is refreshed, button changes to 'following'. How can i manage state of the button using provider??
Ive created a provider for this purpose as follows
import 'package:flutter/material.dart';
class ButtonProvider with ChangeNotifier {
bool isSelected = false;
void setButtonState(bool value) {
isSelected = value;
notifyListeners();
}
bool? get buttondata {
return isSelected;
}
}

Flutter and GetX - Widget doesn't redraw when I update my RxObject

Here the existant :
My IssueController
Rx<GitlabIssue> selectedIssue = new GitlabIssue().obs;
RxList<GitlabIssue> issues = <GitlabIssue>[].obs;
void changeIssueState(GitlabIssueState state) async {
var stateValue = _getGitLabIssueStateValue(state);
bool isInternet = await Utils().isInternet();
if (isInternet) {
var resp = await _issueProvider.changeGitlabIssueState(
projectId, selectedIssue.value.iid, stateValue);
if (resp.statusCode == 200) {
Get.snackbar(
'Issue state changed',
'Issue is $stateValue',
);
var issueIndex = issues.indexOf(selectedIssue.value);
selectedIssue.value.state =
selectedIssue.value.state == 'opened' ? 'closed' : 'opened';
issues[issueIndex] = selectedIssue.value;
gitLabIssueBox.put(projectId, issues);
} else
Get.snackbar(
'Issue state not changed', 'Issue state was not correctly changed');
} else
print('No connectivity');
}
My view
Widget _getButtonStatus() {
return Obx(() {
Color stateColor = _issueController.selectedIssue.value.state == 'closed'
? Colors.green
: Colors.red;
return OutlinedButton(
onPressed: () {
_issueController.selectedIssue.value.state == 'closed'
? _issueController.changeIssueState(GitlabIssueState.reopen)
: _issueController.changeIssueState(GitlabIssueState.close);
},
style: OutlinedButton.styleFrom(
//primary: Colors.white,
//backgroundColor: Colors.teal,
side: BorderSide(color: stateColor, width: 1),
),
child: Obx(
() => Text(
_issueController.selectedIssue.value.state == 'closed'
? 'Reopen issue'
: 'Close issue',
style: TextStyle(color: stateColor),
),
),
);
});
}
I update the value of my selectedIssue.obs and I put the widget in an Obx() => function.
I can't figure out why my widget doesn't redraw.
Weirdly, my onPressed function behave correctly; The button stay the same but if I click again on it the status of my issue change correctly.
Please help me !! :D

Flutter - How to give progress bar to on:Pressed() function of a button?

I am fetching data from firebase database in a async function which triggers when the button is pressed. When the data fetching is complete it moves to the next page(next acitivty). So, in this whole process the async on pressed function takes time to execute the whole code. So, i wanted to show a progress bar until the whole code is executed. Can anyone suggest me how can i show a progress bar until the new activity starts.
Here is my code:
FlatButton(
child: Text("Next",style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontFamily: "Calibri",
fontSize: 20)),
color: Colors.blue,
onPressed:() {
elist.then((value)
async {
for (var item in value) {
alleyes.add(new facial(criminal_id: item.criminal_id,
part_size: item.part_size,
link: item.link));
Uint8List bytes = (await NetworkAssetBundle(Uri.parse(item.link)).load(item.link)).buffer.asUint8List();
eye_str.add(String.fromCharCodes(bytes));
}
Navigator.push(context,
MaterialPageRoute(builder: (context)=>App()));
}
);
},
)
You can start by creating a variable called loading.
bool loading = false;
After this, you can set the loading to true when the button gets tapped and display a progress indicator when the loading variable is true
loading
? Center(child: CircularProgressIndicator())
: FlatButton(
child: Text("Next",style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontFamily: "Calibri",
fontSize: 20)),
color: Colors.blue,
onPressed:() {
setState((){
loading = true;
}); // set loading to true here
elist.then((value)
async {
for (var item in value) {
alleyes.add(new facial(criminal_id: item.criminal_id,
part_size: item.part_size,
link: item.link));
Uint8List bytes = (await NetworkAssetBundle(Uri.parse(item.link)).load(item.link)).buffer.asUint8List();
eye_str.add(String.fromCharCodes(bytes));
}
setState((){
loading = false;
}); // set it to false after your operation is done
Navigator.push(context,
MaterialPageRoute(builder: (context)=>App()));
}
);
},
)

flutter like_button on tap increment the value in the server

I used the like button flutter package from https://pub.dev/packages/like_button
to include like button to my list view from api. I have a table which is contain the count of likes and I show them in every item. now I want to increment the count of likes after tap on like button, but the type of function is bool and I can pass item id as parameter. so please help to solve this issue
LikeButton(
onTap: onLikeButtonTapped,
size: 20,
circleColor:
CircleColor(start: Colors.pink, end: Colors.pinkAccent),
bubblesColor: BubblesColor(
dotPrimaryColor: Colors.red,
dotSecondaryColor: Colors.redAccent,
),
likeBuilder: (bool isLiked) {
return Icon(
Icons.favorite,
color: isLiked ? Colors.pink : Colors.pink[300],
size: 20,
);
},
likeCount: news[index].count_like,
countBuilder: (int count, bool isLiked, String text) {
var color = isLiked ? Colors.grey[700] : Colors.grey[600];
Widget result;
if (count == 0) {
result = Text(
"love",
style: TextStyle(color: color),
);
} else
result = Text(
text,
style: TextStyle(color: color),
);
return result;
},
),
and here is the predefined function which is provided by the package developer
Future<bool> onLikeButtonTapped(bool isLiked) async{
<!-- send your request here -->
<!-- final bool success= await sendRequest(); -->
<!-- if failed, you can do nothing -->
<!-- return success? !isLiked:isLiked; -->
return !isLiked;
}
I am not sure if this could solve your problem, but I also had a similar situation to pass arguments through the function so I modified the function and somehow solved the issue. Hope it helps.
I used ontap like this:
onTap: (isLiked) {
return changedata(
isLiked,
);
},
and then the function,
Future<bool> changedata(status) async {
//your code
return Future.value(!status);
}
}