我想更新'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);
),
);
}
uj5u.com熱心網友回復:
嘗試這個:
有你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: () {},
),
);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/489268.html
