Home > Enterprise >  How to change the value and the function of a button on flutter?
How to change the value and the function of a button on flutter?

Time:01-19

I have a function named saveData which is executed on pressing a button. 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. this is the button code:

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

CodePudding user response:

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: saving ? Finish : saveData,
  child: saving ? 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 saving = false;

  Future saveData() async {

    saving = 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),)
    );

    saving = false;

    setState(() {    });

  }

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

This will produce a result like:

State 1

enter image description here

State 2

enter image description here

CodePudding user response:

You need state management.

State Management

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

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. 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.

    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

  • Related