Created
June 25, 2024 04:25
-
-
Save Chematronix/6ee0734e5d0dc8471395a0da9d302914 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() { | |
runApp(BundleOptParamsTest()); | |
} | |
class BundleOptParamsTest extends StatelessWidget { | |
BundleOptParamsTest({super.key}); | |
final testData = [ | |
{'name': 'Babes', 'number': 123}, | |
{'name': 'Smokes', 'number': 7890}, | |
{'name': 'Rocks', 'number': 09871234} | |
]; | |
final tableProps = { | |
"headingRowColor": MaterialStateColor.resolveWith((states) { | |
return const Color.fromRGBO(200, 100, 50, 1); | |
}), | |
"horizontalMargin": 48.0 | |
}; | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
home: Scaffold( | |
appBar: AppBar( | |
title: const Text('Bundling Optional Parameters to Class Test'), | |
), | |
body: Center( | |
child: DataTableFromMap(tableData: testData, tableProps: tableProps), | |
), | |
)); | |
} | |
} | |
class DataTableFromMap extends StatelessWidget { | |
final List tableData; | |
final Map tableProps; | |
const DataTableFromMap({ | |
super.key, | |
required this.tableData, | |
this.tableProps = const {}, | |
}); | |
@override | |
Widget build(BuildContext context) => createDataTableFromMap(tableData); | |
DataTable createDataTableFromMap(tableData) { | |
// Properties must be symbols, "symbolize" props | |
final props = symbolizeKeys({ | |
"columns": _createColumns(tableData.first), | |
"rows": _createRows(tableData), | |
...tableProps, | |
}); | |
print(props); | |
return Function.apply(DataTable.new, [], props); | |
} | |
List<DataColumn> _createColumns(sampleRow) { | |
return [ | |
for (final e in sampleRow.entries) | |
DataColumn(label: Text(e.key.toString()), numeric: (e.value is num)) | |
]; | |
} | |
List<DataRow> _createRows(tableData) { | |
return [ | |
for (final row in tableData) | |
DataRow(cells: [ | |
for (final v in row.values) | |
DataCell(Text(v is String ? v : v.toString().asThousands)) | |
]) | |
]; | |
} | |
} | |
/// Return a numeric string formatted in thousands. | |
/// Example: -123456.toString().asThousands() returns -123,456 | |
extension on String { | |
String get asThousands { | |
final numberDigits = List.from(split('')); | |
int index = numberDigits.length - 3; | |
while (index > 0) { | |
numberDigits.insert(index, ','); | |
index -= 3; | |
} | |
return numberDigits.join(); | |
} | |
} | |
// Transform the keys of `map` into Symbols so it can be used as named arguments with `Function.apply()` | |
Map<Symbol, dynamic> symbolizeKeys(Map<String, dynamic> map) { | |
return map.map((k, v) => MapEntry(Symbol(k), v)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment