当我从一个页面导航到另一个页面时,当我返回到出现该按钮的页面时,该按钮并不保留其状态。例如,如果我按下该按钮并在返回到第一页时转到第二页,则该按钮处于未按下状态。请帮助我
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)
),
);
},
),
),
],
),
);
}
}
型
主页.dart第一页)
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(第二页)
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,
),
)
);
}
}
型
(主要. dart )
2条答案
按热度按时间fdx2calv1#
我认为当你调用按钮并传递参数:updateButtonState时,你需要将从updateButtonState获取的bool值存储到另一个变量中。
mzmfm0qo2#
你可以使用
AutomaticKeepAliveClientMixin
mixin来保留你的底部导航窗口小部件的状态。在类中添加它,如下所示。class _HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin{
然后在构建小部件中添加超级构建。
字符串
然后在整个构建小部件下面添加这个。
型
确保对底部导航器中的每个小部件都执行此操作,以便在用户离开页面后,所有小部件都不会丢失其状态。