如何在构建上下文中获取共享首选项

How to get shared prefernces in build context

我正在使用 flutter 制作小部件 AppBar Drawer 并将数据保存在 SharedPReferences 中... 这是我的 Drawer.dart: class AppDrawer 扩展了 StatefulWidget {

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

class _AppDrawerState extends State<AppDrawer> {
  SharedPreferences prefs;

  Future<void> logOut() async {
    final prefs = await SharedPreferences.getInstance();

    prefs.clear();
    Navigator.pushReplacementNamed(
      context,
      '/login',
    );
  }

  @override
  Widget build(BuildContext context) {
    final deviceSize = MediaQuery.of(context).size;
    return Drawer(
      child: ListView(
        children: <Widget>[
          DrawerHeader(
            child: Text(prefs.getString('first_name')),
            decoration: BoxDecoration(
              color: Colors.red,
            ),
          ),
          ListTile(
            leading: Text('LogOut'),
            onTap: logOut,
          ),
        ],
      ),
    );
  }
}

我使用它注销的方式正在努力清除它们,但是当我想在小部件构建中使用它时,它给我一个空响应... 我正在尝试 prefs.getString('first_name') 但它给了我 null :( 我在这里做错了什么??

你需要像这样实现它。

class _AppDrawerState extends State<AppDrawer> {
  
  String name = "";
  SharedPreferences prefs;

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

  getName() async {
    final prefs = await SharedPreferences.getInstance();
    setState((){
      name = prefs.getString('first_name');
    });
  }

  Future<void> logOut() async {
    prefs.clear();
    Navigator.pushReplacementNamed(
      context,
      '/login',
    );
  }

  @override
  Widget build(BuildContext context) {
    final deviceSize = MediaQuery.of(context).size;
    return Drawer(
      child: ListView(
        children: <Widget>[
          DrawerHeader(
            child: Text(this.name),
            decoration: BoxDecoration(
              color: Colors.red,
            ),
          ),
          ListTile(
            leading: Text('LogOut'),
            onTap: logOut,
          ),
        ],
      ),
    );
  }
}

await SharedPreferences.getInstance(); 是一个异步调用,您不能在 initState 方法或构建小部件方法中进行异步调用。因此,我创建了一个单独的函数来获取首选项,然后更新了状态变量 name.