0

我想将保存在 App Bar 中 SharedPreference 类对象的键中的值呈现为文本,我必须在小部件的 initState 中声明以下代码。

initState() {
    // TODO: implement initState
    super.initState();
    debugPrint("Runed");
    _getPrefs();
    SharedPreferences.getInstance().then((prefs) {
      setState(() => prefs = prefs);
    });
    
  }

我的 _getPrefs() 代码是:

 SharedPreferences prefs;

  Future<dynamic> _getPrefs() async {
    prefs = await SharedPreferences.getInstance();
    return prefs;
  }

我的 AppBar 代码是:

appBar: AppBar(
        title: Text(prefs.getString("username")),
        centerTitle: true,
      ),

小部件的主体:

  body: ListView(
        children: [
          FutureBuilder(
              future: _getPrefs(),
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  return Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.only(left: 5, top: 5, right: 5),
                        child: Container(
                          width: double.infinity,
                          padding: EdgeInsets.only(left: 5),
                          decoration: BoxDecoration(
                            color: Colors.white54,
                            shape: BoxShape.rectangle,
                            borderRadius: BorderRadius.circular(25.0),
                            boxShadow: [
                              BoxShadow(blurRadius: 2, color: Colors.white)
                            ],
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Container(
                                width: 100,
                                height: 100,
                                margin: EdgeInsets.only(
                                    top: 3, left: 10, bottom: 10),
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  shape: BoxShape.circle,
                                  image: DecorationImage(
                                      image: NetworkImage(
                                          prefs.getString("photoUrl")),
                                      fit: BoxFit.fill),
                                ),
                              ),


                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    prefs.getString("username"),
                                    style: TextStyle(
                                        fontSize: 22,
                                        color: Colors.black45,
                                        fontWeight: FontWeight.bold),
                                  ),
                                  Text(prefs.getString("email"))
                                ],
                              ),


                              /*  Text(
                            prefs.getString("email").toString(),
                            style: TextStyle(fontSize: 18, color: Colors.white70),
                          )*/
                            ],
                          ),
                        ),
                      ),
                    ],
                  );
                } else {
                  return Center(child: Text('False'));
                }
              }),
        ],
      ),

从一个屏幕导航到要在 AppBar 中呈现文本的屏幕时,我确实成功获得了结果,但控制台中确实显示了一些错误,这很烦人。请帮忙告诉原因和解决方法!控制台中的错误是这样的:

Reloaded 14 of 873 libraries in 3,092ms.
I/flutter (20249): Runed

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building ProfileDetail(dirty, state: _ProfileDetailState#6aebe):
The method 'getString' was called on null.
Receiver: null
Tried calling: getString("username")

The relevant error-causing widget was: 
  ProfileDetail file:///D:/All%20Data/My%20Projects/Mine%20Created%20Flutter%20Projects/food_delivery_app/lib/main.dart:268:53
When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1      _ProfileDetailState.build (package:food_delivery_app/ProfileDetails/profileDetail.dart:36:27)
#2      StatefulElement.build (package:flutter/src/widgets/framework.dart:4744:28)
#3      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4627:15)
#4      StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4800:11)
...
════════════════════════════════════════════════════════════════════════════════════════════════════
4

1 回答 1

1

问题是它SharedPreferences.getInstance异步的,但是您在不能的同步方法中调用它await。因此,您AppBar正在构建之前SharedPreferences.getInstance返回,意思prefsnull.

一个简单的解决方案是检查 nullprefs并返回一个空白或默认字符串,直到setState使用非 null 调用prefs

appBar: AppBar(
  title: Text(prefs?.getString("username") ?? ''),
  centerTitle: true,
),
于 2020-12-04T04:53:55.733 回答