Flutter共享首选项在应用重启后获取数据

时间:2019-05-03 17:15:49

标签: flutter

我已经实现了用于存储当前登录用户的共享首选项,用户登录后每次都可以获取用户名,但是重新启动应用程序后,用户名消失了,但是当前用户仍处于登录状态。我附上了gif,以获得更好的解释。下面是我的代码。

enter image description here

main.dart

Future<void> main() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var usernamee = prefs.getString('yourusername');
print(usernamee);
runApp(MaterialApp(
  home: usernamee == null
      ? LoginPage()
      : MainPage(
          username: username,
        )));
}

String username = '';

loginpage.dart

class LoginPage extends StatefulWidget {
@override
LoginPageState createState() => LoginPageState();
}

class LoginPageState extends State<LoginPage> {

TextEditingController user = new TextEditingController();
TextEditingController pass = new TextEditingController(); 

String txtmsg = '';

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

Future<bool> _onWillPop() {
return showDialog(
      context: context,
      builder: (context) => new AlertDialog(
            title: new Text('Are you sure?'),
            content: new Text('Do you want to exit an App'),
            actions: <Widget>[
              new FlatButton(
                onPressed: () => Navigator.of(context).pop(false),
                child: new Text('No'),
              ),
              new FlatButton(
                onPressed: () => Navigator.of(context).pop(true),
                child: new Text('Yes'),
              ),
            ],
          ),
    ) ??
    false;
}

Future<List> _login() async {
SharedPreferences prefs = await SharedPreferences.getInstance();

final response =
    await http.post("http://192.168.1.2/login/login.php", body: {
  "username": user.text,
  "password": pass.text,
});

var datauser = json.decode(response.body);

if (datauser.length == 0) {
  setState(() {
    txtmsg = "Username or password is wrong, please try again.";
    Fluttertoast.showToast(msg: txtmsg);
  });
} else {
  if (datauser[0]['level'] == 'admin') {
    prefs.setString('yourusername', '$username');
    Navigator.pushReplacement(
        context,
        MaterialPageRoute(
            builder: (BuildContext ctx) => MainPage(
                  username: username,
                )));
  }

  setState(() {
    username = datauser[0]['username'];
  });
}
print(username);
return datauser;
}

final logo = Hero(
tag: 'hero',
child: CircleAvatar(
  backgroundColor: Colors.transparent,
  radius: 48.0,
  child: Image.asset('assets/images/ic_launcher.png'),
),
);

final forgotLabel = FlatButton(
child: Text(
  'Forgot password?',
  style: TextStyle(color: Colors.black54),
),
onPressed: () {},
);

@override
Widget build(BuildContext context) {
ScreenUtil.instance = ScreenUtil.getInstance()..init(context);
ScreenUtil.instance =
    ScreenUtil(width: 750, height: 1334, allowFontScaling: true);

return WillPopScope(
    onWillPop: _onWillPop,
    child: Scaffold(
        body: Center(
      child: ListView(
        shrinkWrap: true,
        padding: EdgeInsets.only(left: 24.0, right: 24.0),
        children: <Widget>[
          logo,
          SizedBox(height: 48.0),
          Center(
            child: FormUI(),
          )
        ],
      ),
    )));
}

Widget FormUI() {
return new Column(
  children: <Widget>[
    TextFormField(
      controller: user,
      decoration: InputDecoration(
        hintText: 'Username',
        contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 20.0),
        border:
            OutlineInputBorder(borderRadius: BorderRadius.circular(20.0)),
      ),
      validator: validateusername,
    ),
    SizedBox(height: 18.0),
    TextFormField(
      controller: pass,
      obscureText: true,
      decoration: InputDecoration(
        hintText: 'Password',
        contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 20.0),
        border:
            OutlineInputBorder(borderRadius: BorderRadius.circular(20.0)),
      ),
      validator: validatepassword,
    ),
    SizedBox(
      height: ScreenUtil.getInstance().setHeight(40),
    ),
    RaisedButton(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(24),
      ),
      onPressed: () => _login(),
      padding: EdgeInsets.all(12),
      color: Colors.lightBlueAccent,
      child: Text('Log In', style: TextStyle(color: Colors.white)),
    ),
    forgotLabel,
  ],
);
}

String validateusername(String value) {
if (value.length == 0) {
  return "Name is Required";
}

return null;
}

String validatepassword(String value) {
if (value.length == 0) {
  return "Password is Required";
}

return null;
}
}

mainpage.dart

class MainPage extends StatefulWidget {
MainPage({this.username});
final String username;

@override
MainPageState createState() => MainPageState();
}

class MainPageState extends State<MainPage> {
Future<bool> _onWillPop() {
return showDialog(
      context: context,
      builder: (context) => new AlertDialog(
            title: new Text('Are you sure?'),
            content: new Text('Do you want to exit an App'),
            actions: <Widget>[
              new FlatButton(
                onPressed: () => Navigator.of(context).pop(false),
                child: new Text('No'),
              ),
              new FlatButton(
                onPressed: () => Navigator.of(context).pop(true),
                child: new Text('Yes'),
              ),
            ],
          ),
    ) ??
    false;
}

void showWifiAlert() async {
var wifiEnabled = await getWifiStatus();
if (wifiEnabled) {
  //Do stuff
} else {
  AlertDialog(
    title: Center(
      child: Text('Alert'),
    ),
    content: Row(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        Expanded(
          child: Text(
            'Please connect to the internet',
            textAlign: TextAlign.center,
            style: TextStyle(
              color: Colors.red,
            ),
          ),
        )
      ],
    ),
    actions: <Widget>[
      FlatButton(
        child: Text(
          'Ok',
        ),
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),
    ],
  );
}
}

Future<bool> getWifiStatus() async {
try {
  final result = await InternetAddress.lookup('google.com');
  if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
    print('connected');
    return true;
  }
} on SocketException catch (_) {
  print('not connected');
  return false;
}
}

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

}

@override
Widget build(BuildContext context) {
String username;
print(username);
showWifiAlert();

return WillPopScope(
  onWillPop: _onWillPop,
  child: Scaffold(
      appBar: AppBar(
        title: Text('My App'),
      ),
      body: Center(
        child: Text(
          widget.username,
        ),
      ),
      drawer: new DrawerOnly()),
);
}
}

class DrawerOnly extends StatefulWidget {
@override
DrawerOnlyState createState() => DrawerOnlyState();
}

class DrawerOnlyState extends State<DrawerOnly> {
@override
Widget build(BuildContext ctxt) {
return new Drawer(
    child: new ListView(
  children: <Widget>[
    new UserAccountsDrawerHeader(
      accountName: Text('$username'),
      accountEmail: null,
      currentAccountPicture: CircleAvatar(
        child: FlutterLogo(size: 42.0),
        backgroundColor: Colors.white,
      ),
    ),
    new ListTile(
      leading: Icon(Icons.library_music),
      title: Text('Fragment 1'),
      onTap: () {
        Navigator.pop(ctxt);
        Navigator.push(ctxt,
            new MaterialPageRoute(builder: (ctxt) => new FirstFragment()));
      },
    ),
    new ListTile(
      leading: Icon(Icons.movie),
      title: Text('Fragment 2'),
      onTap: () {
        Navigator.pop(ctxt);
        Navigator.push(ctxt,
            new MaterialPageRoute(builder: (ctxt) => new SecondFragment()));
      },
    ),
    new ListTile(
      leading: Icon(Icons.exit_to_app),
      title: Text('Logout'),
      onTap: () async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.remove('yourusername');
        Navigator.pushReplacement(ctxt,
            MaterialPageRoute(builder: (BuildContext ctx) => LoginPage()));
        /* Navigator.pop(ctxt);
        Navigator.pushReplacementNamed(ctxt, '/landingpage'); */
      },
    ),
  ],
));
}
}

即使重新启动应用程序,如何获取用户名?

5 个答案:

答案 0 :(得分:0)

不在main方法中获取initState上的值。

答案 1 :(得分:0)

var username;
getUsername() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  username = prefs.getString('yourusername');
}

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

答案 2 :(得分:0)

我已经弄清楚了,我必须将此代码添加到mainpage.dart中。下面是代码段。

loadUsername() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
  username = prefs.getString('yourusername');
});
}

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

答案 3 :(得分:0)

我在启动画面上这样使用它,效果很好

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

  token() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String token = prefs.getString('userToken');
    Timer(Duration(milliseconds: 1000), () {
      if (token == null || token == '') {
        Navigator.pushNamed(context, '/login');
      } else {
        Navigator.pushNamed(context, '/home');
      }
    });
  }

答案 4 :(得分:0)

检查此网址

Shared Preferences in Flutter cannot save and read List

希望对您有所帮助。