Flutter:使用子部件更新一个值

我有一个 login_screen 父级,它有一个 password_textfield 作为一个子代。emailpassword 父部件中的数据发生变化时。

父小组件。

EmailTextField(email, focus, (value) {
                          setState(() {
                            email = value;
                          });
                        })

父部件: 子部件:

import 'package:flutter/material.dart';

class EmailTextField extends StatefulWidget {
  final FocusNode focus;

  String email;

  final Function onChange;

  EmailTextField(this.email, this.focus, this.onChange);

  @override
  _EmailTextFieldState createState() => _EmailTextFieldState();
}

class _EmailTextFieldState extends State<EmailTextField> {

  
  @override
  Widget build(BuildContext context) {
return TextFormField(
  onChanged: (value){
    setState(() {
      widget.email = value;
    });
    widget.onChange(value);
  },
  decoration: InputDecoration(labelText: 'Email'),
  textInputAction: TextInputAction.next,
  keyboardType: TextInputType.emailAddress,
  onFieldSubmitted: (v) {
    FocusScope.of(context).requestFocus(widget.focus);
  },
);
  }
}

解决方案:

使用回调函数。

import 'package:flutter/material.dart';

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String email='email';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          EmailTextField(
            onChanged: (value) {
              setState(
                () {
                  email = value;
                },
              );
            },
          ),
          FlatButton(
            onPressed: () {
              //perform some action here
            },
            child: Text('Login'),
          ),
          Text(email),
        ],
      ),
    );
  }
}

class EmailTextField extends StatelessWidget {

  final Function onChanged;
  EmailTextField({this.onChanged});

  @override
  Widget build(BuildContext context) {
    return TextField(
      onChanged: onChanged,
    );
  }
}

给TA打赏
共{{data.count}}人
人已打赏
未分类

<Uncaught RangeError: Maximum call stack size exceeded> 有谁能解决这个问题吗?

2022-9-8 20:54:36

未分类

如何在表中分出今天的日期(或查找间隔id天)?

2022-9-8 20:54:38

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索