How can i maintain the state of button in flutter?

0

i m creating an application in which i have to change the state of a button save the state. and afterwards when that page is open again then the changed state should be displayed.

for example: if i click on the favorite button then its state gets changed from unselected to selected so after this when i closed the app and open it again then the favorite button should be in selected state rather than in unselected state.

please help me out with this issue.

i have used a variable is which the value is stored and then i m checking the condition .

import 'package:EventsApp/Models/EventModel.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;
import 'package:favorite_button/favorite_button.dart';
import 'package:shared_preferences/shared_preferences.dart';

class DetailPage extends StatefulWidget {
  final String image;
  final EventModel value;

  const DetailPage({Key key, this.image, @required this.value})
      : super(key: key);
  @override
  _DetailPageState createState() => _DetailPageState();
}

class _DetailPageState extends State<DetailPage> {
  String eventId;
  String userId;
  bool isPartcipated = false;
  bool isfavorite;

  Future<http.Response> participateinEvent() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var uid = prefs.getString('userId');
    var eveid = prefs.getString('eventId');
    var res = await http.post(
        'http://10.0.2.2:8080/eventusermapping/addParticipant/' +
            uid +
            '/' +
            eveid);
    print(res.body);
    Fluttertoast.showToast(
      msg: 'Participation Successful',
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.BOTTOM,
      timeInSecForIos: 1,
    );
  }

  Future<http.Response> addfavorite() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var uid = prefs.getString('userId');
    var eveid = prefs.getString('eventId');
    var res = await http
        .post('http://10.0.2.2:8080/event/addtoFavorites/' + uid + '/' + eveid);
    Fluttertoast.showToast(
      msg: 'Added to favorite',
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.BOTTOM,
      timeInSecForIos: 1,
    );
    setState(() {
      isfavorite = true;
    });
  }

  Future<http.Response> removefavorite() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var uid = prefs.getString('userId');
    var eveid = prefs.getString('eventId');
    var res = await http.post(
        'http://10.0.2.2:8080/event/removeFromFavorites/' + uid + '/' + eveid);
    Fluttertoast.showToast(
      msg: 'Removed from favorite',
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.BOTTOM,
      timeInSecForIos: 1,
    );
    setState(() {
      isfavorite = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: Color(0xffffffff)),
          onPressed: () => Navigator.of(context).pop(),
        ),
        centerTitle: true,
        backgroundColor: Colors.lightBlue[900],
        elevation: 0.0,
        title: new Text("Event Details",
            style: const TextStyle(
                color: const Color(0xffffffff),
                fontWeight: FontWeight.w500,
                fontStyle: FontStyle.normal,
                fontSize: 19.0)),
      ),
      body: Container(
        child: SingleChildScrollView(
          child: Column(
            children: [
              Container(
                width: double.infinity,
                height: 400.0,
                child: Stack(
                  children: [
                    Positioned(
                      top: 0,
                      left: 0,
                      right: 0,
                      bottom: 90,
                      child: Container(
                        decoration: BoxDecoration(
                          image: DecorationImage(
                            image: NetworkImage('${widget.value.coverimg}'),
                            fit: BoxFit.fitWidth,
                          ),
                        ),
                        // child: Column(
                        //   children: [
                        //     IconButton(
                        //       icon: Icon(Icons.arrow_back),
                        //       onPressed: () => Navigator.pop(context),
                        //       iconSize: 30.0,
                        //       color: Colors.lightBlue[900],
                        //     ),
                        //   ],
                        // ),
                      ),
                    ),
                    Positioned(
                      top: 270,
                      left: 20,
                      right: 20,
                      bottom: 0,
                      child: Card(
                        elevation: 0.5,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(25.0),
                        ),
                        child: Padding(
                          padding: EdgeInsets.all(15.0),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                    '${widget.value.name}',
                                    style: TextStyle(
                                        fontSize: 23.0,
                                        fontWeight: FontWeight.bold,
                                        color: Colors.lightBlue[900]),
                                  ),
                                ],
                              ),
                              Row(
                                children: [
                                  Icon(
                                    Icons.location_on,
                                    color: Colors.grey,
                                    size: 20,
                                  ),
                                  SizedBox(width: 12.0),
                                  Text(
                                    " Kalyan west",
                                    style: TextStyle(
                                        fontSize: 18,
                                        color: Colors.lightBlue[900]),
                                  ),
                                ],
                              ),
                              Row(
                                children: [
                                  Icon(
                                    Icons.calendar_today,
                                    color: Colors.grey,
                                    size: 20,
                                  ),
                                  SizedBox(width: 12.0),
                                  Text(
                                    '${widget.value.date}',
                                    style: TextStyle(
                                        fontSize: 17,
                                        color: Colors.lightBlue[900]),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                width: double.infinity,
                child: Column(
                  children: [
                    SizedBox(height: 12.0),
                    ListTile(
                      leading: CircleAvatar(
                        radius: 25,
                        backgroundImage:
                            NetworkImage('${widget.value.eventheadphoto}'),
                      ),
                      title: Text(
                        '${widget.value.eventheadname}',
                        style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 20,
                            color: Colors.lightBlue[900]),
                      ),
                      subtitle: Text(
                        "Event Head",
                        style: TextStyle(fontSize: 17, color: Colors.grey),
                      ),
                    ),
                    SizedBox(height: 15.0),
                    Padding(
                      padding: EdgeInsets.symmetric(horizontal: 18),
                      child: Text(
                        '${widget.value.description}',
                        textAlign: TextAlign.left,
                        style: TextStyle(
                            fontSize: 19, color: Colors.lightBlue[900]),
                      ),
                    ),
                    SizedBox(height: 20.0),
                    Container(
                      child: Row(
                        children: [
                          Padding(
                            padding: const EdgeInsets.only(left: 70.0),
                            child: Center(
                              child: SizedBox(
                                width: 190,
                                child: isPartcipated
                                    ? RaisedButton(
                                        onPressed: null,
                                        shape: RoundedRectangleBorder(
                                            borderRadius:
                                                BorderRadius.circular(30.0)),
                                        color: Colors.grey,
                                        child: Text(
                                          "Participated",
                                          style: TextStyle(
                                              color: Colors.white,
                                              fontSize: 18.0,
                                              letterSpacing: 1.5),
                                        ),
                                        disabledColor: Colors.black12,
                                        disabledElevation: 1,
                                        disabledTextColor: Colors.black,
                                      )
                                    : RaisedButton(
                                        onPressed: () {
                                          participateinEvent();
                                          setState(() {
                                            isPartcipated = !isPartcipated;
                                          });
                                        },
                                        shape: RoundedRectangleBorder(
                                            borderRadius:
                                                BorderRadius.circular(30.0)),
                                        color: Colors.lightBlue[900],
                                        child: Text(
                                          "Participate",
                                          style: TextStyle(
                                              color: Colors.white,
                                              fontSize: 18.0,
                                              letterSpacing: 1.5),
                                        ),
                                      ),
                              ),
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 50.0),
                            child: Container(
                              decoration: BoxDecoration(
                                  // borderRadius: BorderRadius.circular(50),
                                  // color: Colors.blue,
                                  // border:
                                  //     Border.all(width: 1, color: Colors.grey),
                                  ),
                              child: FavoriteButton(
                                isFavorite: false,
                                valueChanged: (isfavorite) {
                                  if (isfavorite) {
                                    addfavorite();
                                  } else {
                                    removefavorite();
                                  }
                                },
                              ), //IconButton(
                              //     iconSize: 35,
                              //     color: Colors.redAccent[400],
                              //     icon: Icon(Icons.favorite_border),
                              //     tooltip: 'Add to Favorite',
                              //     onPressed: () {}),
                            ),
                          )
                        ],
                      ),
                    ),
                    SizedBox(height: 30.0)
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

android
flutter
dart
asked on Stack Overflow Jan 25, 2021 by Sonal Sawant • edited Jan 25, 2021 by Sonal Sawant

4 Answers

1

You not storing the button state in addFavourite method.

SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool('stateOfButton', true);

When you open your app again, you can get the button state like how you get for the userId and eventId.

prefs.getBool('stateOfButton');
answered on Stack Overflow Jan 25, 2021 by John Joe
0

you can use this package flutter shared preferences

you should make get and set methods

class StorageService {

     Future<String> getTokenAsync() async { 
        SharedPreferences instances = await getInstanceAsync(); 
        String stringValue = instances.getString(Constant.userToken); 
        return stringValue;   } 
    
      Future<void> setTokenAsync(String token) async { 
        SharedPreferences instances = await getInstanceAsync(); 
        instances.setString(Constant.userToken, token);   } } 
    
    
     String token = await _storageService.getTokenAsync();
    
     _storageService.setTokenAsync(entity.token); 
answered on Stack Overflow Jan 25, 2021 by Mustafa yıldiz • edited Jan 25, 2021 by Mustafa yıldiz
0

I don't know if it's possible to just rewrite the initial value of the variables for the following executions of the app. What is possible to do is to store this values somehow, and load them before loading the screen with the favorite button.

What i would do is to use path provider(https://pub.dev/packages/path_provider) and store something like(lets suppose we are talking about movies)

"user":{
"favorited movies" : [
                  12
                  23
                 ]
}

and then before loading the button, checking the movie id is in the user favorited movies array. You can find a good example of how exactly would you store in the complete example in https://flutter.dev/docs/cookbook/persistence/reading-writing-files

answered on Stack Overflow Jan 25, 2021 by user202684
0

If you think about the standard way to deal with State management in your app I suggest you look into BLoC. It requires an initial learning curve with it but it is worth it.

Feel free to find more info in the 'Counter' example on the website

https://bloclibrary.dev/#/gettingstarted

Here is another good talk by Felix, who maintains bloc library

https://www.youtube.com/watch?v=knMvKPKBzGE&t=2327s

answered on Stack Overflow Jan 25, 2021 by Herman Kravchenko

User contributions licensed under CC BY-SA 3.0