首页 > 解决方案 > 如何在颤动中保持按钮的状态?

问题描述

我正在创建一个应用程序,我必须在其中更改按钮的状态并保存状态。之后,当该页面再次打开时,应显示更改后的状态。

例如:如果我单击收藏按钮,则其状态从未选中更改为已选中,因此在此之后当我关闭应用程序并再次打开它时,收藏按钮应处于选中状态而不是未选中状态。

请帮我解决这个问题。

我使用了一个变量来存储值,然后我检查条件。

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)
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

标签: androidflutterdart

解决方案


addFavourite您没有在方法中存储按钮状态。

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

当您再次打开您的应用程序时,您可以获得按钮状态,就像您如何获得userIdand一样eventId

prefs.getBool('stateOfButton');

推荐阅读