Dispongo de un proyecto de Flutter en el que leo el archivo de pubspec.yaml
y cargo el contenido obtenido en un Map
gracias, entre otras cosas, a la funcionalidad ofrecida por el paquete de yaml.
[./lib/src/providers/file_provider.dart]
import 'package:flutter/services.dart' show rootBundle;
import 'package:yaml/yaml.dart';
class _FileProvider {
_FileProvider();
//...
Future<Map> cargarDataYamlToMap(String fileUrl) async {
final resp = await rootBundle.loadString(fileUrl);
Map<dynamic, dynamic> dataMap = loadYaml( resp );
return dataMap;
}
}
final fileProvider = _FileProvider();
Luego, el Map obtenido (o, más bien YamlMap
), recibido dentro de un FutureBuilder
es mandado al método _listaDinamic
dónde es recorrido, recursivamente, para llegar a construir un List<Widget>
con sus ListTile
y/o ExpansionTile
según el elemento recorrido sea un par de clave(String)/valor(NO siendo un Map
) o un par de clave(String)/valor(siendo Map
).
[./lib/src/pages/pub_spec_page.dart]
class PubSpecPage extends StatefulWidget {
@override
_PubSpecPageState createState() => _PubSpecPageState();
}
class _PubSpecPageState extends State<PubSpecPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
S.of(context).pubSpecTitle,
),
actions: <Widget>[
IconButton(
tooltip: 'EXPAND :: Desplegando Todos',
icon: Icon(Icons.unfold_more),
onPressed: () {
print('EXPAND :: Desplegando Todos');
},
),
IconButton(
tooltip: 'COLLAPSE :: Replegando Todos',
icon: Icon(Icons.unfold_less),
onPressed: () {
print('COLLAPSE :: Replegando Todos');
},
),
],
),
body: _listaDinamic(),
);
}
Widget _listaDinamic() {
return FutureBuilder(
future: fileProvider.cargarDataYamlToMap('pubspec.yaml'),
builder: ( context, AsyncSnapshot<Map<dynamic, dynamic>> snapShot ) {
//print(snapShot.data);
if(snapShot.hasData) {
return ListView(
children: _crearItems( snapShot.data, 0 ),
);
} else if (snapShot.hasError) {
return Text('ERROR: ${snapShot.error}');
}
String txtMsg = 'Esperando el resultado...';
return Text(
txtMsg,
);
},
);
}
List<Widget> _crearItems( Map<dynamic, dynamic> data, int indentLevel, [int indexTile] ) {
final List<Widget> items = [];
data.entries.forEach((e) {
var widgetTemp;
if( e.value.runtimeType.toString() == 'YamlList' ) {
//NECESARIO convertir el valor en un List...
List<dynamic> values = List.from(e.value);
List<Widget> subItems = [];
for(var subItem in values) {
widgetTemp = ListTile(
leading: Icon(Icons.fiber_manual_record, color: languagesProvider.getColorByLanguageCode( actualLanguageCodeConstant, 'indentLevelOptions', (indentLevel+1), 'iconColor' ),),
title: Text( '$subItem' ),
);
if (indentLevel > 0) {
widgetTemp = Padding(
padding: EdgeInsets.only(left: languagesProvider.getDoubleOptionByLanguageCode( actualLanguageCodeConstant, 'indentLevelOptions', indentLevel, 'paddingLeft' )),
child: widgetTemp,
);
}
if(widgetTemp != null)
subItems.add( widgetTemp );
widgetTemp = null;
}//for
widgetTemp = ExpansionTile(
leading: Icon(Icons.fiber_manual_record, color: languagesProvider.getColorByLanguageCode( actualLanguageCodeConstant, 'indentLevelOptions', indentLevel, 'iconColor' ),),
title: Text( e.key ),
children: subItems,
);
} else if( e.value.runtimeType.toString() == 'String'
|| e.value.runtimeType.toString() == 'bool'
|| e.value.runtimeType.toString() == 'int'
|| e.value.runtimeType.toString() == 'double' ) {
widgetTemp = ListTile(
leading: Icon(Icons.fiber_manual_record, color: languagesProvider.getColorByLanguageCode( actualLanguageCodeConstant, 'indentLevelOptions', indentLevel, 'iconColor' ),),
title: Text( e.key ),
subtitle: Text( '${e.value}' ),
);
} else {//Siendo YamlMap
Map<String, dynamic> mapValue;
if( e.value.runtimeType.toString() == 'YamlMap' ) {
mapValue = Map<String, dynamic>.from(e.value);
}
widgetTemp = ExpansionTile(
leading: Icon(Icons.fiber_manual_record, color: languagesProvider.getColorByLanguageCode( actualLanguageCodeConstant, 'indentLevelOptions', indentLevel, 'iconColor' ),),
title: Text( e.key ),
children: _crearItems( mapValue, (indentLevel + 1), (indexTile) ),
);
}//No o Si es YamlMap
if (indentLevel > 0) {
widgetTemp = Padding(
padding: EdgeInsets.only(left: languagesProvider.getDoubleOptionByLanguageCode( actualLanguageCodeConstant, 'indentLevelOptions', indentLevel, 'paddingLeft' )),
child: widgetTemp,
);
}
if(widgetTemp != null)
items.add( widgetTemp );
});
return items;
}
}
Todo correcto hasta aquí.
Por un lado, lo que pretendo es que al expandir otro ExpansionTile
, el anterior que se haya abierto, sea cerrado automáticamente.
En mis búsquedas sobre temas relacionados, he visto cuestiones relacionadas con las propiedades key
, initiallyExpanded
y onExpansionChanged
de los ExpansionTile
. Pero no he conseguido lo que pretendía.
He llegado a probar lo que sigue:
de primeras, he añadido una nueva propiedad
selected
en la clase dePubSpecPage
y, cuando se recorre eldata
, he añadido una propiedadkey
a cada nuevoListTile
yExpansionTile
al que se le asigna unindexTile + 1
para que, supuestamente, cadakey
de cada elemento sea único.class _PubSpecPageState extends State<PubSpecPage> { int selected = 0; //... widgetTemp = ListTile( leading: Icon(Icons.fiber_manual_record, color: languagesProvider.getColorByLanguageCode( actualLanguageCodeConstant, 'indentLevelOptions', (indentLevel+1), 'iconColor' ),), title: Text( '$subItem' ), //----------------------------------------------------- key: Key((indexTile + 1).toString()), ); //...
luego, en los
ExpansionTile
, además, añado elinitiallyExpanded
y elonExpansionChanged
://... indexTile++; //----------------------------------------------------- widgetTemp = ExpansionTile( leading: Icon(Icons.fiber_manual_record, color: languagesProvider.getColorByLanguageCode( actualLanguageCodeConstant, 'indentLevelOptions', indentLevel, 'iconColor' ),), title: Text( e.key ), children: subItems, //----------------------------------------------------- key: Key((indexTile).toString()), initiallyExpanded : indexTile==selected, onExpansionChanged: ((newState){ if(newState) setState(() { Duration(seconds: 20000); selected = indexTile; }); else setState(() { selected = -1; }); }), );
Pero el resultado de todo esto es el recibir toda esta serie de excepciones:
de primeras estas dos excepciones:
════════ Exception caught by widgets library ═══════════════════════════════════ The following assertion was thrown building MediaQuery(MediaQueryData(size: Size(411.4, 683.4), devicePixelRatio: 2.6, textScaleFactor: 1.0, platformBrightness: Brightness.light, padding: EdgeInsets.zero, viewPadding: EdgeInsets.zero, viewInsets: EdgeInsets.zero, physicalDepth: 1.7976931348623157e+308, alwaysUse24HourFormat: true, accessibleNavigation: false, highContrast: false,disableAnimations: false, invertColors: false, boldText: false)): 'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: line 263 pos 16: 'child == null || indexOf(child) > index': is not true. Either the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause. In either case, please report this assertion by filing a bug on GitHub: https://github.com/flutter/flutter/issues/new?template=BUG.md The relevant error-causing widget was ListView lib\…\pages\pub_spec_page.dart:81 When the exception was thrown, this was the stack #2 RenderSliverMultiBoxAdaptor._debugVerifyChildOrder package:flutter/…/rendering/sliver_multi_box_adaptor.dart:263 #3 RenderSliverMultiBoxAdaptor.debugChildIntegrityEnabled=.<anonymous closure> package:flutter/…/rendering/sliver_multi_box_adaptor.dart:238 #4 RenderSliverMultiBoxAdaptor.debugChildIntegrityEnabled= package:flutter/…/rendering/sliver_multi_box_adaptor.dart:240 #5 SliverMultiBoxAdaptorElement.performRebuild package:flutter/…/widgets/sliver.dart:1255 #6 SliverMultiBoxAdaptorElement.update package:flutter/…/widgets/sliver.dart:1191 ... ════════════════════════════════════════════════════════════════════════════════ ════════ Exception caught by widgets library ═══════════════════════════════════ A RenderSliverPadding expected a child of type RenderSliver but received a child of type RenderErrorBox. The relevant error-causing widget was ListView lib\…\pages\pub_spec_page.dart:81 ════════════════════════════════════════════════════════════════════════════════
y, luego, esta excepción repetida 23 de veces seguidas (cantidad de supuestos elementos a construir dentro del
List<Widget>
):════════ Exception caught by widgets library ═══════════════════════════════════ 'package:flutter/src/widgets/framework.dart': Failed assertion: line 3949 pos 14: 'owner._debugCurrentBuildTarget == this': is not true. The relevant error-causing widget was ListView lib\…\pages\pub_spec_page.dart:81 ════════════════════════════════════════════════════════════════════════════════
Ojalá alguien tenga pueda suministrar la ayuda necesaria para conseguir el propósito deseado de cerrar el elemento anterior en el momento que se despliega otro.
Por otro lado, en el appBar
de la página, he dispuesto dos iconos: uno para expandir todos los ExpansionTile
y otro para colapsar todos los ExpansionTile
.
¿Alguna idea de cómo llegar a conseguir estas dos funcionalidades de expandir/colapsar todos los ExpansionTile
al pulsar el correspondiente icono?
Saludos.