在类及其状态的有状态小部件中定义构造函数

时间:2019-07-17 09:05:47

标签: flutter dart

我正在flutter应用程序中创建一个登录页面,该页面需要一个构造器,该构造器也需要参数(goToWelcomeListener,enterAnimation),如下所示:

    abstract class GoToWelcomeListener {
      void onGoToWelcomeTap();
    }

    class LoginScreen extends StatefulWidget {

    final GoToWelcomeListener goToWelcomeListener;
    final LoginEnterAnimation enterAnimation;

   LoginScreen(
     {@required AnimationController controller,
     @required this.goToWelcomeListener})
    : this.enterAnimation = new LoginEnterAnimation(controller);

  State<StatefulWidget> createState() {
   return new LoginScreenState();
   }
  }

  class LoginScreenState extends State<LoginScreen> {

  final GoToWelcomeListener goToWelcomeListener;
  final LoginEnterAnimation enterAnimation;
  final userNameController = TextEditingController();
  final passwordController = TextEditingController();
  final formKey = GlobalKey<FormState>();
  final URL = "https://gam3ity.com/";

  LoginScreenState(
    {@required AnimationController controller,
    @required this.goToWelcomeListener})
    : this.enterAnimation = new LoginEnterAnimation(controller);

如您所见,我必须两次定义构造函数才能使其正常工作,并且不会给我错误,因为如果我只是在状态本身而不是在类中对其进行定义,则它不会将其识别为构造函数,并且如果我在没有状态的类中声明了它,那么我将无法在状态cuz中使用任何参数,因为它是在类而不是状态中初始化的。

然后,当我在另一个文件中调用构造函数时,如图所示:

 "/LoginScreen": (BuildContext context) => LoginScreen()

这些是它给我的警告:

warning: The parameter 'controller' is required. (missing_required_param at 
[gam3ity_aa] lib\main.dart:30)
warning: The parameter 'goToWelcomeListener' is required. 
(missing_required_param at [gam3ity_aa] lib\main.dart:30)
warning: The parameter 'goToWelcomeListener' is required. 
(missing_required_param at [gam3ity_aa] lib\screens\login\login_page.dart:34)
warning: The parameter 'controller' is required. (missing_required_param at 
[gam3ity_aa] lib\screens\login\login_page.dart:34)

我想念什么?

1 个答案:

答案 0 :(得分:0)

因此!您已将AnimationController和goToWelcomeListener标记为必需参数。但是您只是叫LoginScreen()->缺少必需的参数

LoginScreen(
 {@required AnimationController controller,
 @required this.goToWelcomeListener})
: this.enterAnimation = new LoginEnterAnimation(controller);