简体   繁体   English

如何修复:必须初始化不可为 null 的实例字段“userFuture”?

[英]How to Fix : Non-nullable instance field 'userFuture' must be initialized?

This is my code for main.dart:这是我的 main.dart 代码:

 class HomePage extends StatefulWidget {
  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
Future userFuture; //error is here

  Future<List<String>> getData() async {
    var databaseRef2 = FirebaseDatabase.instance.reference();
    databaseRef2 = FirebaseDatabase.instance.reference().child("Sliders");
    DatabaseEvent event = await databaseRef2.once();
    Map<dynamic, dynamic> values =
        event.snapshot.value as Map<dynamic, dynamic>;
    values.forEach((key, values) {
      imgList.add(values["img"]);
    });
    return imgList;
  }

  }
}

If I declare Future as:如果我将 Future 声明为:

Future userFuture;

I get this error:我收到此错误:

Non-nullable instance field 'userFuture' must be initialized.
Try adding an initializer expression, or a generative constructor that initializes it

Please tell me how to fix it?请告诉我如何解决? Thanks in advance提前致谢

As per flutter null-safety try to add?根据 flutter 尝试添加空安全

 Future? userFuture;

Or或者

late Future  userFuture;

Well from sdk 2.12 onwards, dart supports null-safety那么从sdk 2.12开始,dart支持null-safety
there are two ways to fix this error, since you haven't mentioned the use of userFuture.有两种方法可以修复此错误,因为您没有提到 userFuture 的使用。

  1. add late keyboard before the initialisation late Future userFuture在初始化late Future userFuture之前添加 late keyboard
  2. add null safety operator Future? userFuture添加 null 安全操作员Future? userFuture Future? userFuture

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM