I give two buttons to choose a gender to the user, and I want the uso can ,choose but when not only row rebuild, the gender value will update. I can do itthe with provider but I know this can do with callbackfunctions. I read, I tried but I coldn't , in addition can you give me a sources about this to learn. If title is bad, feel free to change
import 'package:flutter/material.dart';
class UserCreateView extends StatefulWidget {
const UserCreateView({Key? key}) : super(key: key);
@override
State<UserCreateView> createState() => UserCreateViewState();
}
class UserCreateViewState extends State<UserCreateView> {
bool? gender;
void changeGender(bool genderChoose) {
gender = genderChoose;
setState(() {});
}
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Form(
key: _formKey,
child: Column(
children: [
ElevatedButton(
onPressed: () {},
child: const Text('I dont want to be rebuild, fix it'),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
changeGender(true);
},
style: ElevatedButton.styleFrom(
primary: gender != true
? const Color.fromARGB(255, 92, 161, 207)
: const Color.fromARGB(255, 37, 131, 41),
),
child: const Text(
'man',
),
),
Padding(
padding: const EdgeInsets.all(12.0),
child: ElevatedButton(
onPressed: () {
changeGender(false);
},
style: ElevatedButton.styleFrom(
primary: gender == true
? const Color.fromARGB(255, 92, 161, 207)
: const Color.fromARGB(255, 37, 131, 41),
),
child: const Text(
'woman',
),
),
),
],
),
],
),
),
),
);
}
}
CodePudding user response:
You can use ValueNotifier
with ValueListenableBuilder
in this case.
class UserCreateView extends StatelessWidget {
const UserCreateView({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final _formKey = GlobalKey<FormState>();
final ValueNotifier<bool?> gender = ValueNotifier(null);
return SafeArea(
child: Scaffold(
body: Form(
key: _formKey,
child: Column(
children: [
ElevatedButton(
onPressed: () {},
child: const Text('I dont want to be rebuild, fix it'),
),
ValueListenableBuilder(
valueListenable: gender,
builder: (context, value, child) => Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
gender.value = true;
},
style: ElevatedButton.styleFrom(
primary: gender.value != true
? const Color.fromARGB(255, 92, 161, 207)
: const Color.fromARGB(255, 37, 131, 41),
),
child: const Text(
'man',
),
),
Padding(
padding: const EdgeInsets.all(12.0),
child: ElevatedButton(
onPressed: () {
gender.value = false;
},
style: ElevatedButton.styleFrom(
primary: gender.value == true
? const Color.fromARGB(255, 92, 161, 207)
: const Color.fromARGB(255, 37, 131, 41),
),
child: const Text(
'woman',
),
),
),
],
),
),
],
),
),
),
);
}
}