Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

android - How can i maintain the state of button in flutter?

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,
            

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...