在 Flutter 中初始化后无法更新字符串变量

萨德塔班

我想更新'inputform.dart'中'holecode'变量的新值,然后将这个新值获取到'otpscreen.dart'每次我尝试获取'holecode'字符串变量的值时的问题我得到了初始化它的“默认”值。我尝试将“holecode”变量设置为,late String holecode;但每次尝试获取它的值时,它都会在第二个屏幕中返回 Null。

inputform.dart:

import 'package:flutter/material.dart';
class Inputform extends StatefulWidget {
  List<String> code = ["","","","","",""];
  String holeCode = "default";
  @override
  State<Inputform> createState() => InputformState();
}

class InputformState extends State<Inputform> {
  @override
  Widget build(BuildContext context) {
    return TextFormField(
              onChanged: (value) {
                setState(() {
                  widget.code[0] = value;
                  widget.holeCode = widget.code[0] + 222205;
                });
                if (value.length == 1) {
                  FocusScope.of(context).nextFocus();
                 }
                }
               ),
              },

otp.dart:

import 'package:flutter/material.dart';

class OtpVerification extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => Otp();
}
class Otp extends State<OtpVerification> {
  final Inputform ani= new Inputform ();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        child: 
            FlatButton(
              onPressed: () {
                // trying to print the new value in this screen but it 
                //return the default value 'default'
                print(ani.holeCode);
      ),
    );
  }
约斯特

尝试这个:

有你InputForm喜欢的:

class Inputform extends StatefulWidget {
  final ValueChanged<String> onHoleCodeChanged;

  const Inputform({
    Key? key,
    required this.onHoleCodeChanged,
  }) : super(key: key);
  @override
  State<Inputform> createState() => InputformState();
}

class InputformState extends State<Inputform> {
  List<String> code = ["", "", "", "", "", ""];
  String holeCode = "default";
  @override
  Widget build(BuildContext context) {
    return TextFormField(onChanged: (value) {
      setState(() {
        code[0] = value;
        holeCode = code[0] + "222205";
        widget.onHoleCodeChanged(holeCode);
      });
      if (value.length == 1) {
        FocusScope.of(context).nextFocus();
      }
    });
  }
}

让你的OTP课像这样:

class OtpVerification extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => Otp();
}

class Otp extends State<OtpVerification> {
  late Inputform ani;

  @override
  void initState() {
    ani = Inputform(
      onHoleCodeChanged: (v) {
        setState(() {
          aniHoleCode = v;
        });
      },
    );
    super.initState();
  }

  String aniHoleCode = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FlatButton(
        child: Text("Button"),
        onPressed: () {print(aniHoleCode);},
      ),
    );
  }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章