Tengo el siguiente caso.
Primera pantalla: listado los clientes de API.
Segunda pantalla: para registro y actualización.
Para actualizar los cambios utilizo Provider.
El problema es: cuando ejecuto los métodos de guardar o actualizar y ejecuto nuevamente el método que lista los clientes. Claro, la lista me trae los datos actualizados. Sin embargo, la vista no refleja lso cambios.
Me di cuenta que si ejecuto métodos desde la ventana principal. Si escucha los cambios y renderiza la pantalla con los datos actuazalidos.
Aquí agrego el código completo.
--- Pantalla principal ---
class ClienteScreen extends StatelessWidget {
const ClienteScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
return ChangeNotifierProvider(
create: (_) {
final controller = ClienteController(
const ClienteState(
loading: true,
searchResult: false,
),
clientRepository: context.read(),
globalLoadRepository: context.read(),
);
controller.findAll();
return controller;
},
child: Scaffold(
appBar: AppBar(
title: const TextCustomWidget(
text: 'Clientes',
fontFamily: 'SemiBold',
fontSize: 18,
),
actions: [
Padding(
padding: const EdgeInsets.only(right: 10),
child: IconButton(
onPressed: () {
Navigator.pushNamed(context, 'add_cliente');
},
icon: SvgPicture.asset(
'assets/svg/plus.svg',
width: 20,
height: 20,
colorFilter: const ColorFilter.mode(
Colors.black,
BlendMode.srcIn,
),
),
),
),
],
),
body: SafeArea(
child: LayoutBuilder(
builder: (context, contraints) => RefreshIndicator(
onRefresh: context.read<ClienteController>().findAll,
child: SingleChildScrollView(
physics: const BouncingScrollPhysics(),
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Column(
children: [
//Doc: Separador
SizedBox(height: size.height * 0.02),
const ClienteSearchWidget(),
// Listado de clientes
SizedBox(height: size.height * 0.03),
ListClientWidget(size: size)
],
),
),
),
),
),
),
);
}
}
class ListClientWidget extends StatelessWidget {
const ListClientWidget({
super.key,
required this.size,
});
final Size size;
@override
Widget build(BuildContext context) {
final controller = Provider.of<ClienteController>(context);
final state = controller.state;
final size = MediaQuery.of(context).size;
if (state.loading) {
return _LoadingIndicatorWidget(size: size);
}
return GridView.builder(
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: state.cliente?.length ?? 0,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 16,
mainAxisSpacing: 16,
childAspectRatio: 0.7,
),
itemBuilder: (_, index) {
if (controller.state.cliente == null) {
return const _EmptyInfoWidget();
}
return Container(
decoration: BoxDecoration(
color: state.cliente?[index].estado == true
? Colors.grey[100]
: const Color.fromARGB(255, 255, 227, 230),
borderRadius: BorderRadius.circular(10),
),
child: Padding(
padding: const EdgeInsets.only(
left: 10,
right: 10,
bottom: 10,
top: 20,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
IconButton(
onPressed: () {
Navigator.pushNamed(
context,
'add_cliente',
arguments: jsonEncode(state.cliente?[index]),
);
},
icon: SvgPicture.asset(
'assets/svg/edit.svg',
width: 15,
height: 15,
colorFilter: const ColorFilter.mode(
Colors.black54,
BlendMode.srcIn,
),
),
),
],
)
],
),
),
);
},
);
}
}
--- Pantalla de registro y actualización
class AddClienteFormScreen extends StatelessWidget {
const AddClienteFormScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
String param = ModalRoute.of(context)?.settings.arguments as String? ?? '';
return ChangeNotifierProvider(
create: (_) {
final controller = ClienteController(
const ClienteState(
loading: true,
searchResult: false,
),
clientRepository: context.read(),
globalLoadRepository: context.read(),
);
controller.getTipoDocumento();
return controller;
},
child: Scaffold(
body: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
physics: const BouncingScrollPhysics(),
child: Column(
children: [
//Doc: Separador
SizedBox(height: size.height * 0.03),
//Doc: Header
HeaderClientWidget(
title: param.isEmpty ? 'Registrar' : 'Actualizar',
onPressed: () {
Navigator.pop(context);
},
),
// Doc. Formulario
SizedBox(height: size.height * 0.03),
ClientFormWidget(param: param),
],
),
),
),
);
}
}
class ClientFormWidget extends StatefulWidget {
const ClientFormWidget({
Key? key,
this.param,
}) : super(key: key);
final String? param;
@override
State<ClientFormWidget> createState() => _ClientFormWidgetState();
}
class _ClientFormWidgetState extends State<ClientFormWidget> {
@override
void initState() {
// Todo: implement initState
setValues();
super.initState();
}
@override
void dispose() {
// Todo: implement dispose
super.dispose();
}
Map<String, dynamic> values = {
'idClient': 0,
'idTipoIdentificacion': '',
'numeroIdentificacion': '',
'nombreFiscal': '',
'direccion': '',
'correo': '',
'telefono': '',
'estado': 0,
};
final _numeroIdentificacion = TextEditingController();
final _nombreFiscal = TextEditingController();
final _direccion = TextEditingController();
final _correo = TextEditingController();
final _telefono = TextEditingController();
bool _estado = true;
String _tipoIdentificacion = 'C';
final thumbIcon = MaterialStateProperty.resolveWith<Icon?>(
(Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return const Icon(Icons.check, color: Colors.white);
}
return const Icon(Icons.close);
},
);
@override
Widget build(BuildContext context) {
final ClienteController controller = context.watch();
final size = MediaQuery.of(context).size;
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const TextCustomWidget(
text: 'Los campos con (*) son obligatorios',
fontFamily: 'Medium',
fontSize: 15,
color: Color(0xffFF0000),
),
const SizedBox(height: 30),
DropdownButtonFormField2(
value: controller.state.tipoDocumento?.firstWhere(
(element) => element.codigo == _tipoIdentificacion,
),
decoration: InputDecoration(
isDense: true,
contentPadding: EdgeInsets.zero,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
),
),
buttonStyleData: const ButtonStyleData(
height: 60,
padding: EdgeInsets.only(right: 10),
),
iconStyleData: IconStyleData(
icon: SvgPicture.asset('assets/svg/angle-small-down.svg'),
iconSize: 30,
),
dropdownStyleData: DropdownStyleData(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
),
),
isExpanded: true,
hint: const TextCustomWidget(
text: 'Tipo documento (*)',
fontFamily: 'Regular',
fontSize: 15,
),
items: controller.state.tipoDocumento?.map((e) {
return DropdownMenuItem(
value: e,
child: TextCustomWidget(
text: e.descripcion,
fontFamily: 'Regular',
fontSize: 15,
),
);
}).toList(),
onChanged: (value) {
setState(() {
_tipoIdentificacion = value!.codigo;
values['idTipoIdentificacion'] =
value.idTipoIdentificacion;
});
},
validator: (value) {
if (value == null) {
return 'Seleccione un tipo de documento';
}
return null;
},
),
const SizedBox(height: 30),
TextFormField(
controller: _numeroIdentificacion,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: 'N° de documento *',
hintText: 'Ej: 1234567890',
),
onChanged: (value) {
values['numeroIdentificacion'] = value;
},
validator: (value) {
if (value!.isEmpty) {
return 'Ingrese el número de documento';
}
if (value.length < 10 || value.length > 13) {
return 'El número de documento debe tener al menos 8 caracteres';
}
return null;
},
),
const SizedBox(height: 30),
TextFormField(
controller: _nombreFiscal,
decoration: const InputDecoration(
labelText: 'Nombre fiscal *',
hintText: 'Ej: Sociedad S.A.',
),
onChanged: (value) {
values['nombreFiscal'] = value;
},
validator: (value) {
if (value!.isEmpty) {
return 'Ingrese el nombre fiscal';
}
if (value.length < 3) {
return 'El nombre fiscal debe tener al menos 3 caracteres';
}
return null;
},
),
const SizedBox(height: 30),
TextFormField(
controller: _direccion,
decoration: const InputDecoration(
labelText: 'Dirección *',
hintText: 'Ej: Av. Los Alamos',
),
onChanged: (value) {
values['direccion'] = value;
},
validator: (value) {
if (value!.isEmpty) {
return 'Ingrese la dirección';
}
if (value.length < 3) {
return 'La dirección debe tener al menos 3 caracteres';
}
return null;
},
),
const SizedBox(height: 30),
TextFormField(
controller: _correo,
decoration: const InputDecoration(
labelText: 'Email *',
hintText: 'Ej: [email protected]',
),
onChanged: (value) {
values['correo'] = value;
},
validator: (value) {
if (value!.isEmpty) {
return 'Ingrese el email';
}
if (!regExp.hasMatch(value)) {
return 'El email debe tener un formato válido';
}
return null;
},
),
const SizedBox(height: 30),
TextFormField(
controller: _telefono,
keyboardType: TextInputType.phone,
decoration: const InputDecoration(
labelText: 'Teléfono *',
hintText: 'Ej: 0987654321',
),
onChanged: (value) {
values['telefono'] = value;
},
validator: (value) {
if (value!.isEmpty) {
return 'Ingrese el teléfono';
}
if (!regExpNumber.hasMatch(value)) {
return 'El teléfono debe tener un formato válido';
}
return null;
},
),
const SizedBox(height: 20),
if (widget.param != '')
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const TextCustomWidget(
text: 'Estado',
fontFamily: 'Regular',
fontSize: 16,
),
Switch(
thumbIcon: thumbIcon,
value: _estado,
onChanged: (value) {
setState(() {
_estado = value;
});
},
activeColor: Colors.indigo,
),
],
),
const SizedBox(height: 50),
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: () async {
if (!_formKey.currentState!.validate()) return;
values['estado'] = _estado;
if (values['idTipoIdentificacion'] == null) {
values['idTipoIdentificacion'] =
controller.state.tipoDocumento
?.firstWhere(
(element) =>
element.codigo == _tipoIdentificacion,
)
.idTipoIdentificacion;
}
if (values['idTipoIdentificacion'] == null) {
values['idTipoIdentificacion'] = controller
.state.tipoDocumento?.first.idTipoIdentificacion;
}
if (widget.param == '') {
final result = await controller.save(values);
result.when(
(failure) {
_customNotify(
sms: failure.toString(),
color: Colors.red,
);
},
(rsult) {
_customNotify(
sms: 'Registrado correctamente',
color: Colors.green,
);
Navigator.pop(context);
},
);
} else {
final result = await controller.update(values);
result.when(
(failure) {
_customNotify(
sms: failure.toString(),
color: Colors.red,
);
},
(result) {
_customNotify(
sms: 'Actualizado correctamente',
color: Colors.green,
);
Navigator.pop(context);
},
);
}
},
style: ElevatedButton.styleFrom(
backgroundColor: Colors.indigo,
padding: EdgeInsets.symmetric(
horizontal: size.width * 0.3,
vertical: 10,
),
),
child: TextCustomWidget(
text: widget.param == '' ? 'Registrar' : 'Actualizar',
fontFamily: 'Regular',
fontSize: 15,
color: Colors.white,
),
),
),
],
),
)
}
}
---- Controlador
class ClienteController extends StateNotifier<ClienteState> {
ClienteController(
super.state, {
required this.clientRepository,
required this.globalLoadRepository,
});
final ClientRepository clientRepository;
final GlobalLoadRepository globalLoadRepository;
Future<void> getTipoDocumento() async {
final result = await globalLoadRepository.getTypeDoc();
result.when(
(failure) {
state = state.copyWith(
loading: false,
tipoDocumento: null,
);
},
(tipoDocumento) {
state = state.copyWith(
loading: false,
tipoDocumento: tipoDocumento,
);
},
);
}
Future<void> findAll() async {
state = state.copyWith(loading: true);
final result = await clientRepository.findAll();
result.when(
(_) {
state = state.copyWith(loading: false, cliente: null);
},
(cliente) {
state = state.copyWith(loading: false, cliente: cliente);
},
);
}
void setSearchText(String text) {
state = state.copyWith(searchText: text);
}
void clearSearch() {
state = state.copyWith(searchText: null, searchResult: false);
}
Future<void> search() async {
state = state.copyWith(loading: true, searchResult: false);
final result = await clientRepository.search(state.searchText ?? '');
result.when(
(_) {
state = state.copyWith(
loading: false,
cliente: null,
searchResult: false,
);
},
(search) {
state = state.copyWith(
loading: false,
cliente: search,
searchResult: true,
);
},
);
}
Future<Either<HttpRequestFailure, int>> save(
Map<String, dynamic> data,
) async {
state = state.copyWith(loading: true);
final result = await clientRepository.save(data);
result.when(
(failure) {
state = state.copyWith(loading: false, cliente: null);
return Either.left(failure);
},
(result) async {
return Either.right(result);
},
);
return result;
}
Future<Either<HttpRequestFailure, int>> update(
Map<String, dynamic> data,
) async {
final int idCliente = data['idClient'] ?? 0;
final result = await clientRepository.update(data, idCliente);
result.when(
(failure) => state = state.copyWith(loading: false),
(result) {
state = state.copyWith(loading: false);
return Either.right(result);
},
);
return result;
}
Future<Either<HttpRequestFailure, int>> delete(int idCliente) async {
state = state.copyWith(loading: true);
final result = await clientRepository.deleteById(idCliente);
result.when(
(failure) => state = state.copyWith(loading: false),
(result) {
state = state.copyWith(loading: false);
findAll();
return Either.right(result);
},
);
return result;
}
}
--- Manejador de estados de controlador
class ClienteState {
final bool loading;
final List<ClienteModel>? cliente;
final List<TipoDocumentoModel>? tipoDocumento;
final String? searchText;
final bool searchResult;
const ClienteState({
required this.loading,
this.cliente,
this.tipoDocumento,
this.searchText,
required this.searchResult,
});
ClienteState copyWith({
bool? loading,
List<ClienteModel>? cliente,
List<TipoDocumentoModel>? tipoDocumento,
String? searchText,
bool? searchResult,
}) {
return ClienteState(
loading: loading ?? this.loading,
cliente: cliente ?? this.cliente,
tipoDocumento: tipoDocumento ?? this.tipoDocumento,
searchText: searchText ?? this.searchText,
searchResult: searchResult ?? this.searchResult,
);
}
}
--- Manejador de estado global ---
abstract class StateNotifier<State> extends ChangeNotifier {
StateNotifier(this._state) : _oldState = _state;
State _state, _oldState;
bool _mounted = true;
// Create getters
bool get mounted => _mounted;
State get state => _state;
State get oldState => _oldState;
set state(State newState) {
_update(newState);
}
void onlyUpdate(State newState) {
_update(newState, notify: false);
}
void _update(State newState, {bool notify = true}) {
if (_state != newState) {
_oldState = _state;
_state = newState;
if (notify) {
notifyListeners();
}
}
}
@override
void dispose() {
_mounted = false;
super.dispose();
}
}