簡體   English   中英

無法弄清楚如何在 flutter 中使用 SharedPreferences,請幫助:)

[英]Can't figure it out how to use SharedPreferences in flutter, please help :)

我試圖在我的應用程序中制作一個星星計數器,當應用程序關閉並重新打開時,星星的數量應該保持不變,而不是再次從 0 開始。 我所做的就是這個,但它不起作用。

int correctGuesses = 0;

  String language1 = "";
  String language2 = "";
  String language3 = "";

  Widget buildGame() {

    final myController = TextEditingController();

    @override
    void dispose() {
      myController.dispose();
      super.dispose();
    }

    int nextNumber({required int min, required int max}) =>
        min + Random().nextInt(max - min + 1);

    int rowNumber = Random().nextInt(1);
    int columnNumber = nextNumber(min: 1, max: 10);
    final language = languageMatrix[rowNumber][0];
    final sentence = languageMatrix[rowNumber][columnNumber];

    return SingleChildScrollView(
      child: Column(
        children: <Widget> [
          Image.asset('assets/GameLogo_2.png'),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 0),
            child: Container(
              decoration: BoxDecoration(
                color: Colors.teal[200],
                borderRadius: const BorderRadius.all(Radius.circular(10)),
                border: Border.all(color: Colors.black)
              ),
              height: 125,
              child: Center(
                  child: Text(
                    sentence,
                    style: const  TextStyle(fontSize: 17),
                    textAlign: TextAlign.center,
                  )
              ),
            ),
          ),
          Container(height: 20),
          Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget> [
                 Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                  child: SizedBox(
                    width: 200,
                    //height: 70,
                    child: TextField(
                      cursorColor: Colors.teal,
                      controller: myController,
                      decoration: const InputDecoration(
                        border: OutlineInputBorder(),
                        hintText: 'Enter a language',
                      ),
                    ),
                  )
                ),
                TextButton(
                  style: TextButton.styleFrom(
                      textStyle: const TextStyle(fontSize: 20)),
                  onPressed: () {
                    _incrementCounter();
                    if (counter >= 1 && counter <= 3 )
                        {
                          if (myController.text == language)
                          {
                            if (counter == 1)
                            {
                              language1 = language;
                              firstAttempt = myController.text;
                              correctGuesses++;
                            }
                            if (counter == 2)
                            {
                              language2 = language;
                              secondAttempt = myController.text;
                              correctGuesses++;
                            }
                            if (counter == 3)
                            {
                              language3 = language;
                              thirdAttempt = myController.text;
                              correctGuesses++;
                            }
                          }
                          else
                          {
                            if (counter == 1)
                            {
                              language1 = language;
                              firstAttempt = myController.text;
                            }
                            if (counter == 2)
                            {
                              language2 = language;
                              secondAttempt = myController.text;
                            }
                            if (counter == 3)
                            {
                              language3 = language;
                              thirdAttempt = myController.text;
                            }
                          }
                        }
                    if (counter == 3)
                    {
                      if (correctGuesses == 0)
                        {
                          showDialog<String>(
                              barrierDismissible: false,
                              context: context,
                              builder: (BuildContext context) => AlertDialog(
                                title: const Text('Your Score', textAlign: TextAlign.center, style: TextStyle(fontSize: 25),),
                                content: SizedBox(
                                    height: 250,
                                    child: Column(
                                        children: <Widget>[
                                          Row(
                                            mainAxisAlignment: MainAxisAlignment.center,
                                            children: const <Widget>[
                                              Icon(Icons.star_border, size: 70, color: Colors.teal),
                                              Icon(Icons.star_border, size: 70, color: Colors.teal),
                                              Icon(Icons.star_border, size: 70, color: Colors.teal),
                                            ],
                                          ),
                                          Container(height: 15),
                                          Text('Sentence 1: $language1', textAlign: TextAlign.center),
                                          Container(height: 15),
                                          Text('Sentence 2: $language2', textAlign: TextAlign.center),
                                          Container(height: 15),
                                          Text('Sentence 3: $language3', textAlign: TextAlign.center),
                                          Container(height: 15),
                                          const Text('Check your profile to see your total number of stars, or go back home and start a new round!', textAlign: TextAlign.center,)
                                        ]
                                    )
                                ),
                                elevation: 24,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(10),
                                ),
                                actionsAlignment: MainAxisAlignment.spaceAround,
                                actions: <Widget>[
                                  TextButton(
                                    onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (context) => StartPage())),
                                    child: const Text('Home'),
                                  ),
                                  TextButton(
                                    onPressed: () {
                                      Navigator.push(context, MaterialPageRoute(builder: (context) => ProfilePage()));
                                    },
                                    child: const Text('Profile'),
                                  ),
                                ],
                              )
                          );
                        }
                      if (correctGuesses == 1)
                        {
                          showDialog<String>(
                              barrierDismissible: false,
                              context: context,
                              builder: (BuildContext context) => AlertDialog(
                                title: const Text('Your Score', textAlign: TextAlign.center, style: TextStyle(fontSize: 25),),
                                content: SizedBox(
                                    height: 250,
                                    child: Column(
                                        children: <Widget>[
                                          Row(
                                            mainAxisAlignment: MainAxisAlignment.center,
                                            children: const <Widget>[
                                              Icon(Icons.star, size: 70, color: Colors.teal),
                                              Icon(Icons.star_border, size: 70, color: Colors.teal),
                                              Icon(Icons.star_border, size: 70, color: Colors.teal),
                                            ],
                                          ),
                                          Container(height: 15),
                                          Text('Sentence 1: $language1', textAlign: TextAlign.center),
                                          Container(height: 15),
                                          Text('Sentence 2: $language2', textAlign: TextAlign.center),
                                          Container(height: 15),
                                          Text('Sentence 3: $language3', textAlign: TextAlign.center),
                                          Container(height: 15),
                                          const Text('Check your profile to see your total number of stars, or go back home and start a new round!', textAlign: TextAlign.center,)
                                        ]
                                    )
                                ),
                                elevation: 24,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(10),
                                ),
                                actionsAlignment: MainAxisAlignment.spaceAround,
                                actions: <Widget>[
                                  TextButton(
                                    onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (context) => StartPage())),
                                    child: const Text('Home'),
                                  ),
                                  TextButton(
                                    onPressed: () {
                                      //setStarsNumber(correctGuesses);
                                      Navigator.push(context, MaterialPageRoute(builder: (context) => ProfilePage()));
                                    },
                                    child: const Text('Profile'),
                                  ),
                                ],
                              )
                          );
                        }
                      if (correctGuesses == 2)
                        {
                          showDialog<String>(
                              barrierDismissible: false,
                              context: context,
                              builder: (BuildContext context) => AlertDialog(
                                title: const Text('Your Score', textAlign: TextAlign.center, style: TextStyle(fontSize: 25),),
                                content: SizedBox(
                                    height: 250,
                                    child: Column(
                                        children: <Widget>[
                                          Row(
                                            mainAxisAlignment: MainAxisAlignment.center,
                                            children: const <Widget>[
                                              Icon(Icons.star, size: 70, color: Colors.teal),
                                              Icon(Icons.star, size: 70, color: Colors.teal),
                                              Icon(Icons.star_border, size: 70, color: Colors.teal),
                                            ],
                                          ),
                                          Container(height: 15),
                                          Text('Sentence 1: $language1', textAlign: TextAlign.center),
                                          Container(height: 15),
                                          Text('Sentence 2: $language2', textAlign: TextAlign.center),
                                          Container(height: 15),
                                          Text('Sentence 3: $language3', textAlign: TextAlign.center),
                                          Container(height: 15),
                                          const Text('Check your profile to see your total number of stars, or go back home and start a new round!', textAlign: TextAlign.center,)
                                        ]
                                    )
                                ),
                                elevation: 24,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(10),
                                ),
                                actionsAlignment: MainAxisAlignment.spaceAround,
                                actions: <Widget>[
                                  TextButton(
                                    onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (context) => StartPage())),
                                    child: const Text('Home'),
                                  ),
                                  TextButton(
                                    onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (context) => ProfilePage())),
                                    child: const Text('Profile'),
                                  ),
                                ],
                              )
                          );
                        }
                    if (correctGuesses == 3)
                      {
                        showDialog<String>(
                            barrierDismissible: false,
                            context: context,
                            builder: (BuildContext context) => AlertDialog(
                              title: const Text('Your Score', textAlign: TextAlign.center, style: TextStyle(fontSize: 25),),
                              content: SizedBox(
                                  height: 250,
                                  child: Column(
                                      children: <Widget>[
                                        Row(
                                          mainAxisAlignment: MainAxisAlignment.center,
                                          children: const <Widget>[
                                            Icon(Icons.star, size: 70, color: Colors.teal),
                                            Icon(Icons.star, size: 70, color: Colors.teal),
                                            Icon(Icons.star, size: 70, color: Colors.teal),
                                          ],
                                        ),
                                        Container(height: 15),
                                        Text('Sentence 1: $language1', textAlign: TextAlign.center),
                                        Container(height: 15),
                                        Text('Sentence 2: $language2', textAlign: TextAlign.center),
                                        Container(height: 15),
                                        Text('Sentence 3: $language3', textAlign: TextAlign.center),
                                        Container(height: 15),
                                        const Text('Check your profile to see your total number of stars, or go back home and start a new round!', textAlign: TextAlign.center,)
                                      ]
                                  )
                              ),
                              elevation: 24,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(10),
                              ),
                              actionsAlignment: MainAxisAlignment.spaceAround,
                              actions: <Widget>[
                                TextButton(
                                  onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (context) => StartPage())),
                                  child: const Text('Home'),
                                ),
                                TextButton(
                                  onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (context) => ProfilePage())),
                                  child: const Text('Profile'),
                                ),
                              ],
                            )
                        );
                      }
                    }
                    myController.clear();
                  },
                  child: const Text('Guess'),
                )
              ]
            ),
          Container(height: 20),
          Padding(
              padding: const EdgeInsets.symmetric(horizontal: 100, vertical: 5),
              child: Container(
                height: 30,
                decoration: BoxDecoration(
                  color: Colors.teal[200],
                  borderRadius: const BorderRadius.all(Radius.circular(10)),
                border: Border.all(color: Colors.black),
                ),
                child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget> [
                      const Text('Sentence 1/3: '),
                      Text(firstAttempt)
                    ]
                )
              )
          ),
          Padding(
              padding: const EdgeInsets.symmetric(horizontal: 100, vertical: 5),
              child: Container(
                  height: 30,
                  decoration: BoxDecoration(
                    color: Colors.teal[200],
                    borderRadius: const BorderRadius.all(Radius.circular(10)),
                    border: Border.all(color: Colors.black),
                  ),
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget> [
                        const Text('Sentence 2/3: '),
                        Text(secondAttempt)
                      ]
                  )
              )
          ),
          Padding(
              padding: const EdgeInsets.symmetric(horizontal: 100, vertical: 5),
              child: Container(
                  height: 30,
                  decoration: BoxDecoration(
                    color: Colors.teal[200],
                    borderRadius: const BorderRadius.all(Radius.circular(10)),
                    border: Border.all(color: Colors.black),
                  ),
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget> [
                        const Text('Sentence 3/3: '),
                        Text(thirdAttempt)
                      ]
                  )
              )
          ),
          Container(
            height: 10,
          ),
        ]
      ),
    );
  }


  Future<int> getOldStarsNumber() async {
    final SharedPreferences pref = await SharedPreferences.getInstance();
    int oldStarsNumber = (pref.getInt('keyStarsNumber') ?? 0);
    return oldStarsNumber;
  }

  Future<void> updateStarsNumber() async{
    final SharedPreferences pref = await SharedPreferences.getInstance();
    int oldStarsNumber = await getOldStarsNumber();
    int starsNumber = correctGuesses + oldStarsNumber;
    pref.setInt('keyStarsNumber', 0);
  }


這是我使用的第一個 class 的數據,這是我計算星數的地方。

class ProfilePageState extends State<ProfilePage> {

  int? starsNumber;

  @override
  void initState() {
    super.initState();
    setStarsNumber();
  }

  Future<void> setStarsNumber() async {
    final SharedPreferences pref = await SharedPreferences.getInstance();
    starsNumber = pref.getInt('keyStarsNumber');
    setState(() {

    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('My profile, coming soon'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Icon(Icons.star, size: 200, color: Colors.teal,),
            Text('$starsNumber', style: const TextStyle(fontSize: 100)),
          ],
        ),
      ),
    );
  }
}

這是第二個 class,我在其中獲得了該數量的星星並將其放入文本中。 有了這段代碼,星星總數始終保持為0,我不知道該怎么辦,所以請幫忙。 correctGuesses 變量來自上面的小部件 Build,它確實有效……我所想的是,這可能是 correctGuesses 變量失去了它的價值。 我認為我 100% 錯了..但這就是我的想法。 請幫助我,我卡住了:)非常感謝!

我認為您的代碼的問題在於,您在 updateStarsNumber function 中的每次更新時一遍又一遍地初始化共享首選項的實例。 嘗試擁有一個應用程序范圍內的共享首選項實例。 您可以在主 function 中對其進行初始化,將其命名為 prefs,並在需要的地方注入它。

基本上,只調用 await SharedPreferences.getInstance(); 一次在應用程序中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM