【问题标题】:Change button name when the button is clicked单击按钮时更改按钮名称
【发布时间】:2022-01-17 19:49:32
【问题描述】:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:paylater/res/asset_strings.dart';
import 'package:paylater/res/motito_colors.dart';
import 'package:paylater/res/string_en.dart';
import 'package:paylater/res/style.dart';
import 'package:paylater/screens/motito_stepper.dart';
import 'package:paylater/screens/reset_password_verify.dart';
import 'package:paylater/util/validator.dart';
import 'package:paylater/widget/motito_dialog.dart';
import 'package:paylater/widget/motito_flat_button.dart';


class Resetsteps extends StatefulWidget {
@override
_ResetstepsState createState() => _ResetstepsState();
 }

 class _ResetstepsState extends State<Resetsteps> {
 final _formKey = GlobalKey<FormBuilderState>();
 final _phoneController = TextEditingController();


 bool phoneFieldEmpty = true;

 @override
 Widget build(BuildContext context) {
  MotitoDialog md = MotitoDialog(
  context,
  isDismissible: false,
);
md.style(
  borderRadius: 8.0,
  messageTextStyle: CustomTextStyles.kBody.copyWith(
    color: MotitoColors.kNeutralsGrey4,
    fontSize: 14.0,
  ),
);
return MotitoStepper(
  step: 1,
  total: 3,
  leading: GestureDetector(onTap: () {}, child: Icon(CupertinoIcons.arrow_left),), 
  helpMessage: 'I need help on the forgot my password page',
  body: SingleChildScrollView(
    child: FormBuilder(
      key: _formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(height: 50.0),
          Text(
            'Forgot my Password',
            style: CustomTextStyles.kHeader3.copyWith(
              color: MotitoColors.kSecondaryTextColor1,
            ),
          ),
          SizedBox(height: 2.0),
          Text(
            'Please type in your phone number and we will send you a 6 digit code',
            style: CustomTextStyles.kBody.copyWith(
              color: MotitoColors.kNeutralsGrey5,
              fontSize: 14.0,
            ),
          ),
          SizedBox(height: 32.0),
                  textFieldLabel(
                    StringEn.kPhoneNumber,
                    required: true,
                  ),
                  TextFormField(
                    textInputAction: TextInputAction.next,
                    inputFormatters: [
                      FilteringTextInputFormatter.digitsOnly,
                    ],
                    controller: _phoneController,
                    keyboardType: TextInputType.phone,
                    decoration: inputDecoration(
                      context,
                      hint: StringEn.kPhoneHint,
                      prefixText: '(+233)',
                    ),
                    onChanged: (phone) {
                      if (phone != null && phone.isNotEmpty) {
                        setState(() {
                          phoneFieldEmpty = false;
                        });
                      } else {
                        setState(() {
                          phoneFieldEmpty = true;
                        });
                      }
                    },
                    validator: FormBuilderValidators.compose([
                      FormBuilderValidators.minLength(context, 9,
                          errorText: AssetStrings.kInvalidPhone),
                      FormBuilderValidators.maxLength(context, 10,
                          errorText: AssetStrings.kInvalidPhone),
                      Validator.leadingZeroValidator,
                    ]),
                  ),
          SizedBox(height: 8.0),
          SizedBox(height: 120.0),

我是一名初级实习生,被分配了一项任务,即在现有应用中添加新功能。我已经完成了 UI,但无法在我的代码上使用特定功能,这里是按钮的代码,我希望按钮上的文本更改为“正在加载...”。

我能做些什么来实现这一目标?

                         MotitoFlatButton(
                        label: StringEn.kContinue,
                        enabled: !phoneFieldEmpty,
                        onTap: () {
                          if (_formKey.currentState.validate()) {

                            Navigator.push(
                          context,
                          MaterialPageRoute(
                           builder: (context) =>   ResetPasswordVerify()));
                          }
                        },
                      ),
          SizedBox(height: 56.0),
        ],
      ),
    ),
  ),
);
 }
 }

这里也是按钮小部件的代码。

import 'package:flutter/material.dart';
import 'package:paylater/res/motito_colors.dart';
import 'package:paylater/res/style.dart';

const _buttonRadius = 8.0;

class MotitoFlatButton extends StatelessWidget {
final String label;
final VoidCallback onTap;
final Color bg;
final Color textColor;
final Color disabledBg;
final Color disabledTextColor;
final double width;
final bool enabled;

const MotitoFlatButton({
@required this.label,
@required this.onTap,
this.bg = MotitoColors.kMotitoBlue,
this.textColor = Colors.white,
this.disabledBg = MotitoColors.kButtonDisabled,
this.disabledTextColor = MotitoColors.kButtonDisabledText,
this.width = double.infinity,
  this.enabled = true,
 });

  @override
  Widget build(BuildContext context) {
   return Material(
    borderRadius: BorderRadius.circular(_buttonRadius),
   child: InkWell(
    onTap: enabled ? onTap : null,
    borderRadius: BorderRadius.circular(_buttonRadius),
    child: Ink(
      padding: const EdgeInsets.symmetric(vertical: 16.0),
      width: width,
      decoration: BoxDecoration(
        color: enabled ? bg : disabledBg,
        borderRadius: BorderRadius.circular(_buttonRadius),
      ),
      child: Center(
        child: Text(
          label,
          style: CustomTextStyles.kBody
              .copyWith(color: enabled ? textColor : disabledTextColor),
        ),
      ),
    ),
  ),
  );
  }
 }

我已经尽力了,但无法让它发挥作用。

【问题讨论】:

  • 您的解释性文本(“我是一名初级实习生...”)似乎已放置在代码块中。这是一段代码,还是两个文件?
  • 实际上是它的两个文件
  • 好的,谢谢。似乎第一个文件缺少很多结束缩进,第二个文件缺少很多开始缩进。但人们正在回答,所以也许这对读者来说已经足够清楚了。

标签: android firebase flutter dart frontend


【解决方案1】:

每当您想要更改 UI 时,您都必须调用 setState

调用 setState 通知框架内部状态 此对象的更改方式可能会影响用户界面 在这个子树中,这会导致框架为 这个状态对象

因此,在您的特定情况下,我会将该按钮更改为 Statefull 小部件(右键单击 Stateless 和 Refactor),然后在您的 onTap 函数上放置:

  child: ElevatedButton(
    onPressed: () {
      setState(
        () {
          isLoading = true;
        },
      );
    },
    child: isLoading ? Text('Loading...') : Text('Click me'),
  ),

所以现在每当您单击按钮时,它的状态都会发生变化,并且您的 UI 应该会更新

您也可以在此处放置一个加载指示器,而不仅仅是这样的文本:

  child: ElevatedButton(
    onPressed: () {
      setState(
        () {
          isLoading = true;
        },
      );
    },
    child: isLoading
        ? Text('Loading...')
        : Center(
            child: CircularProgressIndicator(
              strokeWidth: 2.0,
            ),
          ),
  ),

【讨论】:

  • 我也会试试这个看看
  • 我做 isLoading 一个 setter 吗??
  • 你可以让你的 isLoading 在你的构建方法之外设置一个布尔值并将其设置为 false
  • 在状态改变后如何禁用按钮的任何提示?
  • @SEYRAMEMMANUELAGBANYO 您可以创建另一个 isButtonWorking 布尔值,将其设置为 true,但按钮的 onTap 将其设置为 false 并禁用 onPressed 功能,就像您更改文本一样正在加载
【解决方案2】:

您可以尝试使用 GestureDetector 包装 Button,并使用 setState 设置您提供给 Button Widget 的 String 的状态,这应该可以:

GestureDetector(
                            onTap:(){
                              setState(() {
                                yourString = "Loading..."
                              });
                            },
                          child: YourButton(yourstring),
                        )

【讨论】:

  • 该代码块中会有两个 onTaps。这行得通吗?请同时查看小部件代码
  • 试试看。或者为您的标签创建一个字符串变量,默认为“StringEn.kContinue”,然后在按钮的 onTap 中创建一个 setState,在其中将变量更改为“正在加载...”
  • 我会试试这个
  • 如果不行就写在这里
猜你喜欢
  • 2018-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-13
相关资源
最近更新 更多