Изменение общих настроек ‘get Int’ вызывалось при нулевом колебании

#flutter #sharedpreferences

#флаттер #sharedpreferences

Вопрос:

Я хочу сохранить данные с помощью общих настроек, но это не работает. Кто-нибудь может мне помочь? Я получаю эту ошибку:

После того, как я нажимаю на кнопку, появляется эта ошибка. Я предполагаю, что проблема заключается либо в кнопке, либо в методе обновления, который вызывается при нажатии кнопки.

Методы set и get int в методе update не работали. Я надеюсь, что смогу помочь вам с этим текстом.

 The following NoSuchMethodError was thrown while handling a gesture:
The method 'getInt' was called on null.
Receiver: null
Tried calling: getInt("userLevel")
   
  

ВОТ МОЙ КОД

 import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Satz extends StatefulWidget {
  @override
  _SatzState createState() => _SatzState();
}

class _SatzState extends State<Satz> {
  static const String USERLEVEL ='userLevel';
  int userLevel = 1;
  SharedPreferences prefs;
  int commacount= 2;
  int i =0;
  String stringValue = '';
  Map<int, String> getsatz ={
    1 : 'Ich finde diese App gut da ich hierdurch die Kommasetzung lerne. ',
    2 : 'Paul wo bist du ?',
    3: 'Wenn das Wetter morgen gut wird können wir uns gerne bei mir treffen',
    4: 'Der Baum der dort steht ist schon über 40 Jahre alt.',
  };
  Map<int,String> rightSatz = {
    1 : 'Ich finde diese App gut, da ich hierdurch die Kommasetzung lerne. ',
    2 : 'Paul, wo bist du ?',
    3: 'Wenn das Wetter morgen gut wird, können wir uns gerne bei mir treffen',
    4: 'Der Baum, der dort steht, ist schon über 40 Jahre alt.',
  };
  Map<int, int> getcommacount ={
    1: 1,
    2:1,
    3:1,
    4:2,
  };  @override
  void initState(){
    readUserLevel();
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    print('refresh');
    return Scaffold(backgroundColor: Colors.deepOrange,
      appBar: AppBar(
        centerTitle: true,
        title: Text('Satz ' userLevel.toString(),
        style: TextStyle(
          color: Colors.black,
          fontSize: 30,
        ),),
        backgroundColor: Colors.deepOrange,),
          body: SingleChildScrollView(
                      child: Column(
                        children: [ 
                          Padding(
                              padding: EdgeInsets.fromLTRB(10, 20, 10, 10),
                            child: Card(
                                color: Colors.yellow,
                                child:
                   
            Padding(
              padding: EdgeInsets.all(5),
                                child: RichText(
                text: TextSpan(
                  children:  newmethod()
                )
                ),
            )

            ),
                            ),
                         RaisedButton(
            shape:RoundedRectangleBorder(
              side: BorderSide(color:Colors.black, width:2.0),
  borderRadius: BorderRadius.circular(10.0),
            ),
            padding: EdgeInsets.fromLTRB(50, 10, 50, 10),
            onPressed: (){
              if (stringValue == rightSatz[userLevel]) {
                if (userLevel >= 4) {
                  setState(() {
                                   updateUserLevel.call(USERLEVEL,1);
                                   //readLevels();
                                   stringValue='';
                  });
                } else {
                  updateUserLevel(USERLEVEL,1);
                  setState(() {
                  updateUserLevel.call(USERLEVEL,1); 
                  //readUserLevel();
                  stringValue ='';
                  });
                }
              } else {print('wrong value');
              }
             // Navigator.push(context, MaterialPageRoute(builder: (context) => Satz()));
            },
            color: Colors.yellow
            ,child:
            Text('Prüfen',
            style: TextStyle(fontSize: 40),),
          ) 
                        ],
                      ),
                  
          ),
          
    );
  }
 newmethod(){

    if (stringValue =='') {

         stringValue = getsatz[userLevel];
    commacount = getcommacount[userLevel];
    print(userLevel);
    }
    return 
    stringValue.split(' ').asMap().entries.map((entry) {
      print('worked as well');
                    String text = entry.value;
                    int index = entry.key;
                    return TextSpan(
                            text: text   " ",
                            style: TextStyle(
                              color: Colors.black,
                              fontSize: 50),
                            recognizer: new TapGestureRecognizer()
                                ..onTap = () {
                                  if (commacount == 1) {
                                  List<String> correctedValue = stringValue.replaceAll(',','').split(' ');
                                  print(correctedValue[index]);
                                  if(!text.contains(',')){
                                    correctedValue[index]  = ',';                      
                                  }
                                  setState(
                                    () {
                                      stringValue = correctedValue.join(' ');
                                    },
                                  );}
                                  if (commacount ==2) {
                                    if (i != commacount) {
                                      List<String> correctedValue stringValue.replaceAll(',',',').split(' ');
                                    
                                  print(correctedValue[index]);
                                  if(!text.contains(',')){
                                    correctedValue[index]  = ',';                      
                                  }
                                  setState(
                                    () {
                                      stringValue = correctedValue.join(' ');
                                      i  ;
                                    },
                                  );
                                  
                                  }else{
                                    List<String> correctedValue = stringValue.replaceAll(',','').split(' ');
                                    setState(() {
                                      i =0;
                                    });
                                    
                                  print(correctedValue[index]);
                                  if(!text.contains(',')){
                                    correctedValue[index]  = ',';                      
                                  }
                                  setState(
                                    () {
                                      stringValue = correctedValue.join(' ');
                                    },
                                  );}
                                  }
                                },
                    );
                  }).toList();
  
  }
   readUserLevel()async{
      prefs = await SharedPreferences.getInstance();
      int userLevel = prefs.getInt(USERLEVEL);
      if (userLevel== null) {
        await prefs.setInt(USERLEVEL, 1);
      }
      setState(() {
        userLevel = userLevel;
      });
    }
    
     void updateUserLevel(String key, int value){
      switch(key){
        case USERLEVEL:{
          int userLevel = prefs.getInt(key);
            userLevel  = value; 
          print(userLevel);
          prefs.setInt(key, value);

        }
        break;
      }
    }
}
  

Я уже пробовал серьезные способы решения этой проблемы. Я был бы очень благодарен, если бы кто-нибудь мог ответить на мой вопрос.

Комментарии:

1. Удалите async / await, поскольку SharedPreferences.getInstance() не возвращает Future , также используйте setState для обновления prefs.SetInt

2. где я могу конкретно добавить setState? Теперь я получаю сообщение об ошибке getInt был вызван при нулевом

3. if(userLevel!= null) { setState(() { userLevel = userLevel; }); }

4. Может, я тупой, но это не работает. Do может вставить часть кода во весь код. Я был бы очень рад 🙂