【问题标题】:How can i maintain the state of button in flutter?如何在颤动中保持按钮的状态?
【发布时间】:2021-04-29 08:51:48
【问题描述】:

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

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

请帮我解决这个问题。

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

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

【问题讨论】:

  • 你可以使用SharedPreferences
  • 不,我试过了,它不起作用,你能举个例子,我该怎么做,可能是我做错了
  • 或许可以向我们展示您的尝试?
  • 好的,我会放代码
  • 我已经添加了你可以看到的代码并给出建议

标签: android flutter dart


【解决方案1】:

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

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

当您再次打开您的应用时,您可以像获得userIdeventId 一样获得按钮状态。

prefs.getBool('stateOfButton');

【讨论】:

    【解决方案2】:

    我不知道是否可以只为应用程序的以下执行重写变量的初始值。可以做的是以某种方式存储这些值,并在使用收藏按钮加载屏幕之前加载它们。

    我要做的是使用路径提供程序(https://pub.dev/packages/path_provider)并存储类似的东西(假设我们在谈论电影)

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

    然后在加载按钮之前,检查电影 ID 是否在用户收藏的电影数组中。您可以在https://flutter.dev/docs/cookbook/persistence/reading-writing-files

    完整示例中找到一个很好的示例,说明您将如何存储

    【讨论】:

      【解决方案3】:

      如果您考虑在应用程序中处理状态管理的标准方法,我建议您研究 BLoC。它需要一个初步的学习曲线,但它是值得的。

      请随时在网站上的“计数器”示例中找到更多信息

      https://bloclibrary.dev/#/gettingstarted

      这是维护 bloc 库的 Felix 的另一个精彩演讲

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

      【讨论】:

        【解决方案4】:

        你可以使用这个包flutter shared preferences

        你应该创建 get 和 set 方法

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

        【讨论】:

        猜你喜欢
        • 2021-08-14
        • 2019-07-01
        • 2020-08-01
        • 2023-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多