【问题标题】:Unhandled Exception: The getter 'name' was called on null未处理的异常:在 null 上调用了 getter 'name'
【发布时间】:2021-07-10 04:26:57
【问题描述】:

Hooolaaa 社区,我有一个非常有趣的问题,我不太明白, 我定义了一个字符串变量(String uName = "";)并通过执行(uName = userCurrentInfo.name;)将我当前的用户名传递给它,之后我在 2 Text Widget(Text('${userCurrentInfo?.名称}',样式:TextStyle(fontSize: 16.0, fontFamily: "Brand Bold"),), 问题 : 它有时不显示用户名,直到我重新启动我的 android studio 并卸载我的应用程序并重新启动,然后它开始工作。而其他时候它只是工作。 我尝试过的: 我曾尝试直接从firebase中的currentUser名称调用,如下所示:( Text('${userCurrentInfo?.name}',) 和这个工作,但我不想每次我想使用这个名字时都重复这个我当前的用户。 感谢您的宝贵时间

这是错误消息: 未处理的异常:NoSuchMethodError:在 null 上调用了 getter 'name'。 收件人:空

class MainScreen extends StatefulWidget
{
  static const String idScreen = "mainScreen";

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

class _MainScreenState extends State<MainScreen> with TickerProviderStateMixin
{
   String uName="";

     void locatePosition() async
  {
    Position position = await Geolocator.getCurrentPosition(desiredAccuracy: 
     LocationAccuracy.high);
    currentPosition = position;

    LatLng latLatPosition = LatLng(position.latitude, position.longitude);
    String address = await AssistantMethods.searchCoordinateAddress(position, context);
    print("This is your Address :: " + address);

    initGeoFireListner();

 =====>     uName =  userCurrentInfo.name; // I have user name stored in my uName String Variable.

     appFirebaseMonitoring();

    AssistantMethods.retrieveHistoryInfo(context);
  }

// I used it my Drawer in the build method 

 @override
  Widget build(BuildContext context) {
    createIconMarker();
    return Scaffold(
      key: scaffoldKey,
      drawer: Container(
        color: Colors.white,
        width: 255.0,
        child: Drawer(
          child: ListView(
            children: [
              //Drawer Header
              Container(
                height: 165.0,
                child: DrawerHeader(
                  decoration: BoxDecoration(color: Colors.white),
                  child: Row(
                    children: [
                      Image.asset("images/user_icon.png", height: 65.0, width: 65.0,),
                      SizedBox(width: 16.0,),
                      Expanded(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(uName, style: TextStyle(fontSize: 16.0, fontFamily: "Brand Bold"),),
                            SizedBox(height: 6.0,),
                            GestureDetector(
                                onTap: ()
                                {
                                  Navigator.push(context, MaterialPageRoute(builder: (context)=> ProfileTabPage()));
                                },
                                child: Text("Visit Profile")
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),

【问题讨论】:

    标签: flutter dart firebase-realtime-database firebase-authentication


    【解决方案1】:

    在 Flutter 中,您需要手动更新小部件的状态。这意味着如果你有一个像var name = "temp" 这样的变量并且你构建了一个像Text(name) 这样的小部件,它将显示temp。那么如果你把name变量改成myName,文字还是会显示temp,那是因为你需要重绘你的布局才能用新的值来构建。

    StatefulWidgetState 中,你有状态(变量),当它们改变时,你需要调用setStatesetState 将使用新状态(变量)重绘您的布局:

    void locatePosition() async {
        Position position = await Geolocator.getCurrentPosition(desiredAccuracy: 
         LocationAccuracy.high);
        currentPosition = position;
    
        LatLng latLatPosition = LatLng(position.latitude, position.longitude);
        String address = await AssistantMethods.searchCoordinateAddress(position, context);
        print("This is your Address :: " + address);
    
        initGeoFireListner();
    
        setState((){ // rebuild this widget with this changes
          uName =  userCurrentInfo.name;
        });
    
        appFirebaseMonitoring();
    
        AssistantMethods.retrieveHistoryInfo(context);
      }
    

    我也没看到你在哪里打电话locatePosition

    调用它的最简单方法是在initState_MainScreenState

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

    如果userCurrentInfo?.name 有效,那么您可以做两件事:

    1. 使 uName 成为全局 getter:
    import '...';
    
    String get uName => userCurrentInfo?.name ?? '';
    
    class ... {
     ...
    }
    
    1. uName初始化为userCurrentInfo?.name
      String uName = "";
    
      @override
      void initState() {
        super.initState();
        uName =  userCurrentInfo?.name ?? '';
      }
    

    【讨论】:

    • 好吧,我试过这样做: setState((){ // 用这个改变重建这个小部件 uName = userCurrentInfo.name; });它没有工作
    • 还有 initState None 工作
    • 我的代码共享整个主屏代码,只是它的1300行代码
    • 缺少很多东西。就像,无论createIconMarker 做什么,你都不应该在build 中调用它。 userCurrentInfo 来自哪里?它是静态全局变量吗?如果是这种情况,您可以使用顶级 getter 来获取用户名并完全删除 uName
    • 您好,Aligator 先生,有空我可以将脚本发给您。因为我不知道它为什么会表现不佳,但是当我使用 userCurrentInfo?.name 时它可以工作。只是想了解我做错了什么以及为什么当我运行应用程序时它会从 firebase 获取名称而其他时候它不起作用(当我定义 uName 变量时)
    猜你喜欢
    • 2022-01-16
    • 2021-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多