skip to Main Content

When I navigate from one page to another, the button does not retain its state when I return to the page on which it appears. For example, if I press the button and go to my second page when I return to the first page, the button is in the unpressed state.
Please help me

import 'package:flutter/material.dart';

class MyButton extends StatefulWidget {
  final bool isButtonConfirmed;
  final Function(bool) updateButtonState;

  const MyButton(
      {Key? key,
      required this.isButtonConfirmed,
      required this.updateButtonState})
      : super(key: key);

  @override
  State<MyButton> createState() => _MyButtonState();
}

class _MyButtonState extends State<MyButton> {
  late bool isPressed = false;

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      style: ButtonStyle(
        backgroundColor:
            MaterialStateProperty.all(isPressed ? Colors.grey : Colors.blue),
        shape: MaterialStateProperty.all<RoundedRectangleBorder>(
          RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8.0),
          ),
        ),
        padding: MaterialStateProperty.all(
          const EdgeInsets.all(10.0),
        ),
      ),
      onPressed: isPressed
          ? null
          : () {
              setState(() {
                isPressed = !isPressed;
                widget.updateButtonState(isPressed);
              });
            },
      child: const Text(
        "Confirmer",
        style: TextStyle(color: Colors.white),
      ),
    );
  }
}

button.dart

import 'package:flutter/material.dart';
import 'package:ace_app/components/button.dart';

class HomePage extends StatefulWidget {
  final bool isButtonConfirmed;
  final Function(bool) updateButtonState;

  const HomePage(
      {Key? key,
      required this.isButtonConfirmed,
      required this.updateButtonState})
      : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  bool isButton = false;

  void updateButton(bool newState) {
    setState(() {
      isButton = newState;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          "ACE PRESENCE",
          style: TextStyle(
            fontFamily: "Poppins",
            fontSize: 20,
            color: Colors.white,
          ),
        ),
        toolbarHeight: 70,
        backgroundColor: Colors.blue,
        actions: [
          PopupMenuButton<String>(
            icon: const Icon(
              Icons.more_vert,
              color: Colors.white,
            ),
            onSelected: (String value) {
              if (value == 'reset') {
                
              }
            },
            itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[
              const PopupMenuItem<String>(
                value: 'reset',
                child: Text(
                  'Réinitialiser',
                  style: TextStyle(fontFamily: "Poppins", fontSize: 15.0),
                ),
              ),
            ],
          ),
        ],
      ),
      body: Column(
        children: [
          const SizedBox(height: 20.0),
          const Padding(
            padding: EdgeInsets.all(15.0),
            child: TextField(
              decoration: InputDecoration(
                prefixIcon: Icon(Icons.search),
                hintText: "Entrez votre nom",
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.all(Radius.circular(25.0)),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: Colors.blue),
                  borderRadius: BorderRadius.all(Radius.circular(25.0)),
                ),
                contentPadding: EdgeInsets.all(15.0),
              ),
            ),
          ),
          const SizedBox(height: 0.0),
          Expanded(
            child: ListView.builder(
              itemCount: 3,
              itemBuilder: (BuildContext context, int index) {
                return Card(
                  margin: const EdgeInsets.symmetric(vertical: 8.0),
                  color: Theme.of(context).scaffoldBackgroundColor,
                  child: ListTile(
                    contentPadding: const EdgeInsets.symmetric(
                      vertical: 8.0,
                      horizontal: 16.0,
                    ),
                    leading: const CircleAvatar(
                      backgroundColor: Colors.blue,
                      child: Icon(
                        Icons.person,
                        color: Colors.white,
                      ),
                    ),
                    title: const Center(child: Text("Nom et prénom")),
                    subtitle: const Center(child: Text("Numéro de téléphone - Classe")),
                    trailing: MyButton(isButtonConfirmed: isButton, updateButtonState: updateButton)
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

home.dart’first page)

import 'package:flutter/material.dart';
import 'package:ace_app/components/text_field.dart';
import 'package:ace_app/components/phone.dart';

class User {
  String nom;
  String classe;
  String num;

  User({required this.nom, required this.classe, required this.num});
}

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

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

class _FormPageState extends State<FormPage> {
  final nameController = TextEditingController();
  final classeController = TextEditingController();
  final numController = TextEditingController();

  List<User> userList = [];

  final _formKey = GlobalKey<FormState>(); // Clé globale pour le formulaire

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          "Formulaire",
          style: TextStyle(
            fontFamily: "Poppins",
            fontSize: 20,
            color: Colors.white,
          ),
        ),
        toolbarHeight: 70,
        backgroundColor: Colors.blue,
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(20),
          child: Form(
            key: _formKey, // Utilisation de la clé pour le formulaire
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                const SizedBox(height: 60),
                const Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      "Bienvenue chez nous",
                      style: TextStyle(
                        fontFamily: "Poppins",
                        fontSize: 20,
                        color: Colors.black54,
                      ),
                    ),
                  ],
                ),
                const Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      "ACE FAMILY",
                      style: TextStyle(
                        fontFamily: "Poppins",
                        color: Colors.blue,
                        fontSize: 35,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 40),
                MyTextfield(
                  controller: nameController,
                  hintText: "Nom et prénoms",
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return 'Veuillez entrer votre nom et prénom';
                    }
                    return null;
                  },
                ),
                const SizedBox(height: 18),
                MyTextfield(
                  controller: classeController,
                  hintText: "Classe",
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return 'Veuillez entrer votre classe';
                    }
                    return null;
                  },
                ),
                const SizedBox(height: 18),
                PhoneNumberField(
                  controller: numController,
                  hintText: "Numéro de téléphone",
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return 'Veuillez entrer votre numéro de téléphone';
                    }
                    return null;
                  },
                ),
                const SizedBox(height: 18),
                GestureDetector(
                  onTap: () {
                    if (_formKey.currentState!.validate()) {
                      // Si la validation est réussie, procédez à l'inscription
                      String name = nameController.text;
                      String classe = classeController.text;
                      String phoneNumber = numController.text;

                      User newUser = User(nom: name, classe: classe, num: phoneNumber);

                      setState(() {
                        userList.add(newUser);
                      });

                      nameController.clear();
                      classeController.clear();
                      numController.clear();

                      for (var user in userList) {
                        print('Nom : ${user.nom}, Classe : ${user.classe}, Numéro : ${user.num}');
                      }

                      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Utilisateur ajouté', style: TextStyle(fontFamily: "Poppins"),),
          duration: Duration(seconds: 5), // Durée d'affichage de la SnackBar
        ),
      );
                    }
                  },
                  child: Container(
                    padding: const EdgeInsets.all(20),
                    decoration: BoxDecoration(
                      color: Colors.blue,
                      borderRadius: BorderRadius.circular(10.0),
                    ),
                    child: const Center(
                      child: Text(
                        "S'inscrire",
                        style: TextStyle(
                          color: Colors.white,
                          fontFamily: "Poppins",
                          fontWeight: FontWeight.w500,
                          fontSize: 20,
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

form.dart(second page)

import 'package:ace_app/pages/form.dart';
import 'package:flutter/material.dart';
import 'package:ace_app/components/bar_bottom.dart';
import 'package:ace_app/pages/home.dart';

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

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool isButton = false;
  int _currentIndex = 0;

  void updateButton(bool newState) {
    setState(() {
      isButton = newState;
    });
  }

  setCurrentIndex(index) {
    setState(() {
      _currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
          body: [HomePage(isButtonConfirmed: isButton, updateButtonState: updateButton,), const FormPage()][_currentIndex],
          bottomNavigationBar: BottomNavigation(
            onIndexChanged: setCurrentIndex,
            currentIndex: _currentIndex,
          ),
        )
    );
  }
}

(main.dart)

2

Answers


  1. I think when you call the button and pass the parameter: updateButtonState, You need to store the bool value that gets from updateButtonState into another variable.

    Login or Signup to reply.
  2. You can use the AutomaticKeepAliveClientMixin mixin to retain the state of your bottom navigator widgets. In the class add it like this.

    class _HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin{

    Then in the build widget, add super build.

    @override
      Widget build(BuildContext context) {
    super.build(context);
    

    Then below the whole build widget add this.

    @override
      bool get wantKeepAlive => true;
    

    Make sure to do this for every of the widgets in the bottom navigator so that all of the widget will not lose its state once the user leaves the page.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search