skip to Main Content

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'),
  ),
),

3

Answers


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

    Login or Signup to reply.
  2. 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

    enter image description here

    After Save Data is tapped

    enter image description here

    Login or Signup to reply.
  3. Basically this is a state management problem.

    you get more information about state management from here

    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),
            ),
          ),
        );
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search