FutureBuilderFlutter初始化状态

jaql4c8m  于 2023-01-06  发布在  Flutter
关注(0)|答案(3)|浏览(141)

我很困惑在哪里我可以实现初始化状态条件为未来的建设者。看看什么是错误的在我的代码。在Flutter文档是指初始化状态为未来的建设者小部件。

` @override
  void initState() {
    super.initState();
    futureLoginuser = loginuser();
  }`

我试图导航后,响应数据arrives.my完整的代码在这里我使用go_router导航新屏幕。

class LoginForm extends StatefulWidget {
  const LoginForm({Key? key}) : super(key: key);

  @override
  LoginFormState createState() {
    return LoginFormState();
  }
}

class LoginFormState extends State<LoginForm> {

  TextEditingController mobileController = TextEditingController();
  TextEditingController passwordController = TextEditingController();
  final _mobileKey = GlobalKey<FormState>();
  final _passwordKey = GlobalKey<FormState>();

  get message => null;

  get messagecode => null;

  get userinfo => null;

  get token => null;

  Future<Loginuser> loginuser(String mobile, String password) async {
    final response = await http.post(
        Uri.parse('https:random.url/api/login'),
        body: {'mobile': mobile, 'password': password});

    if (response.statusCode == 200) {
      return Loginuser.fromJson(jsonDecode(response.body));
      }
    } else {
      throw Exception('Failed to update');
    }
  @override
  Widget build(BuildContext context) {
    return Form(
        key: _mobileKey,
        child: Column(crossAxisAlignment: CrossAxisAlignment.center, children: [
          TextFormField(
            controller: mobileController,
            autofocus: true,
            keyboardType: TextInputType.phone,
            decoration: const InputDecoration(
              border: InputBorder.none,
              hintText: "Enter Your Mobile Number",
            ),
          ),
          TextFormField(
            controller: passwordController,
            key: _passwordKey,
            keyboardType: TextInputType.visiblePassword,
            decoration: const InputDecoration(
              border: InputBorder.none,
              hintText: "Enter Your Password",
            ),
          ),
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 16.0),
            child: ElevatedButton(
                onPressed: () {
                    FutureBuilder<Loginuser>(
                      future: loginuser(mobileController.text.toString(),
                          passwordController.text.toString()),
                      builder: (context, snapshot) {
                        if (snapshot.hasData) {
                          print('snapshsot.hasdata');
                          context.go('/Home');
                        } else if (snapshot.hasError) {
                          return Text('${snapshot.error}');
                        }
                        return const CircularProgressIndicator();
                      },
                    );
                  }
                child: const Text('Submit')),
          ),
        ]));
  }
}

'

6qqygrtg

6qqygrtg1#

你用错FutureBuilder了,它是一个小部件,基于与未来交互的最新快照构建自己。它通常用于构建在某个未来完成时需要输入的小部件。
在您的情况下,请使用以下命令:

//first make the onPressed function async
    child ElevatedButton(
        child: Container(),
        onPressed: () async {
          // then await the future You want to complete and then use `.then()` 
          //method to implement the code that you want to implement when the future is completed
          await loginuser(mobileController.text.toString(),
                  passwordController.text.toString())
              .then((result) {
            print('future completed');
            context.go('/Home');
            // For errors use onError to show or check the errors.
          }).onError((error, stackTrace) {
            print(error);
          });
        });
  • 并使用表单密钥验证方法验证表单是否存在任何错误。*

等待未来完成并做一些事情的唯一方法是直接使用异步函数,如我上面所示,或者使用try/catch方法,这两种方法都可以很好地工作。

xmq68pz9

xmq68pz92#

试试这个

LoginUser? loginUser
 @override
  void initState() async{
    super.initState();
    futureLoginuser = await loginuser();
    ... // 👈 Your navigation here
  }`

尝试通过检查loginUser来使您的构建具有响应性

@override
  Widget build(BuildContext context) {
    futureLoginuser == null ?
                  CircularProgressIndicator() : <Rest of your widget>
   }
k7fdbhmy

k7fdbhmy3#

你试图实现的方式是不正确的,这里有一个很基本的例子要做

class LoginForm extends StatefulWidget {
  const LoginForm({Key? key}) : super(key: key);

  @override
  LoginFormState createState() {
    return LoginFormState();
  }
}

class LoginFormState extends State<LoginForm> {
  TextEditingController mobileController = TextEditingController();
  TextEditingController passwordController = TextEditingController();
  final _formKey = GlobalKey<FormState>();

  // your other variables

  bool isValidating = false;

  @override
  Widget build(BuildContext context) {
    return Form(
        key: _formKey,
        child: Column(crossAxisAlignment: CrossAxisAlignment.center, children: [
          TextFormField(
            controller: mobileController,
            autofocus: true,
            keyboardType: TextInputType.phone,
            decoration: const InputDecoration(
              border: InputBorder.none,
              hintText: "Enter Your Mobile Number",
            ),
          ),
          TextFormField(
            controller: passwordController,
            keyboardType: TextInputType.visiblePassword,
            decoration: const InputDecoration(
              border: InputBorder.none,
              hintText: "Enter Your Password",
            ),
          ),
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 16.0),
            child: isValidating
                ? const CircularProgressIndicator()
                : ElevatedButton(
                    onPressed: () async {
                      if (_formKey.currentState!.validate()) {
                        setState(() {
                          isValidating = !isValidating;
                        });
                        final r = await loginuser(
                            mobileController.text.toString(),
                            passwordController.text.toString());
                        if (r != null) {
                          // save user state locally, using hive or what alternative you want
                          context.go('/Home');
                        } else {
                          ScaffoldMessenger.of(context)
                              .showSnackBar(const SnackBar(
                            content: Text('Failed'),
                          ));
                        }
                        setState(() {
                          isValidating = !isValidating;
                        });
                      }
                    },
                    child: const Text('Submit')),
          ),
        ]));
  }

  Future<Loginuser?> loginuser(String mobile, String password) async {
    final response = await http.post(Uri.parse('https:random.url/api/login'),
        body: {'mobile': mobile, 'password': password});

    if (response.statusCode == 200) {
      return Loginuser.fromJson(jsonDecode(response.body));
    }
    return null;
  }
}

相关问题