简体   繁体   English

如何更改flutter上按钮的值和function?

[英]How to change the value and the function of a button on flutter?

I have a function named saveData which is executed on pressing a button.我有一个名为saveData的 function,它在按下按钮时执行。 I want if I click on the button I execute saveData function and the value of the button become stop then when I click on stop the function should be fininish.我想如果我点击我执行 saveData function 的按钮并且按钮的值变为停止然后当我点击停止时 function 应该完成。 this is the button code:这是按钮代码:

Align(
  alignment: Alignment.bottomCenter,
  child: TextButton(
    onPressed: () {
      saveData();
    },
    child: Text('Save Data'),
  ),
),

One way to achieve what you want is simply to create a flag to control which button (text/action) is shown at any given moment:实现您想要的一种方法是简单地创建一个标志来控制在任何给定时刻显示哪个按钮(文本/操作):

TextButton(
  onPressed: isSaving ? Finish : saveData,
  child: isSaving ? const Text("Stop") : const Text("Save Data"),
)

Try the following working complete sample to see what i mean:试试下面的工作完整示例看看我的意思:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool isSaving = false;

  Future saveData() async {

    isSaving = true;

    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text("Saving data..."),duration: Duration(hours: 1),)
    );

    setState(() {    });

  }

  void Finish() {
    ScaffoldMessenger.of(context).hideCurrentSnackBar();
    ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text("Saving data stopped..."),duration: Duration(seconds: 1),)
    );

    isSaving = false;

    setState(() {    });

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: TextButton(
          onPressed: isSaving ? Finish : saveData,
          child: isSaving ? const Text("Stop") : const Text("Save Data"),
        )
      ),
    );
  }
}

This will produce a result like:这将产生如下结果:

State 1 State 1

在此处输入图像描述

After Save Data is tapped点击保存数据

在此处输入图像描述

You need state management.你需要state管理。

State Management State 管理

This is a way to manage your user interface controls such as text fields, buttons, images, etc. It controls what and when something should display or perform an action.这是一种管理用户界面控件(如文本字段、按钮、图像等)的方法。它控制什么以及什么时候应该显示或执行操作。 More about Flutter state management here更多关于 Flutter state 管理在这里

Codebase Sample代码库示例

    String name = ""; // setting an empty name variable

    Align(
        alignment: Alignment.bottomCenter,
        child: TextButton(
            onPressed: () {
                setState(() {
                    name = "new name"; // updating the name variable with setState
                });
            },
        child: Text('Save Data'),
      ),
    ),

Now, to implement your idea.现在,实现你的想法。 You need a bool variable that changes the state on the button click action.您需要一个布尔变量来更改按钮单击操作上的 state。 To do that, look what I did below为此,看看我在下面做了什么

    bool isClicked = false;

    Align(
        alignment: Alignment.bottomCenter,
        child: TextButton(
            onPressed: () {
                setState(() => isClicked = !isClicked); // change click state
                if (isClicked) {
                    // do something on click
                } else {
                    // do something off click
                }
            },
        child: Text(isClicked ? "Stop" : "Save Data"), // if isClicked display "Stop" else display "Save Data"
      ),
    ),

Another way to do this is to create two different functions.另一种方法是创建两个不同的函数。 One for saving user data, and the other of stop and calling the action based on a bool state.一个用于保存用户数据,另一个用于停止并根据布尔值 state 调用操作。

    onPressed: isSaving ? saveData : stop,

You can use the method above to update your user data as well if any misunderstand or need future help, comment below.您也可以使用上述方法更新您的用户数据,如果有任何误解或需要日后的帮助,请在下方评论。 Bye再见

Basically this is a state management problem.基本上这是一个state的管理问题。

you get more information about state management from here您可以从此处获得有关 state 管理的更多信息

Here a code for solve your problem这是解决您问题的代码

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const HomeView(),
    );
  }
}

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

  @override
  State<HomeView> createState() => _HomeViewState();
}

class _HomeViewState extends State<HomeView> {

  bool _savePressed = false;

  void _save() {
    // TODO do whatever you want
  }

  void _stop() {
    // TODO do whatever you want
  }

  void _onButtonPressed() {
    setState(() {
      _savePressed = !_savePressed;
      _savePressed ? _save() : _stop();
    });
  }

  String get _getButtonText => _savePressed ? "Stop" : "Save";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Align(
        alignment: Alignment.bottomCenter,
        child: TextButton(
          onPressed: _onButtonPressed,
          child: Text(_getButtonText),
        ),
      ),
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM