dynamic_constructor 1.0.0
dynamic_constructor: ^1.0.0 copied to clipboard
A flexible utility to dynamically instantiate classes and invoke constructors using positional and named parameters from dynamic data sources.
import 'package:flutter/material.dart';
import 'package:dynamic_constructor/dynamic_constructor.dart';
void main() {
runApp(const MyApp());
}
class User {
final String name;
final int age;
final String email;
User(this.name, this.age, {required this.email});
@override
String toString() => 'User(name: $name, age: $age, email: $email)';
}
class Product {
final String id;
final String title;
final double price;
Product({required this.id, required this.title, this.price = 0.0});
@override
String toString() => 'Product(id: $id, title: $title, price: $price)';
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Dynamic Constructor Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
User? _user;
Product? _product;
void _createObjects() {
// Creating a User using positional and named arguments
final userConstructor = DynamicConstructor<User>(
User.new,
['John Doe', 30, {'email': 'john@example.com'}],
);
// Creating a Product using only named arguments
final productConstructor = DynamicConstructor<Product>(
Product.new,
{
'id': 'PROD-001',
'title': 'Premium Coffee'
},
);
setState(() {
_user = userConstructor.instance;
_product = productConstructor.instance;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Dynamic Constructor Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (_user != null) ...[
const Text('Created User:'),
Text(_user.toString(), style: const TextStyle(fontWeight: FontWeight.bold)),
const SizedBox(height: 20),
],
if (_product != null) ...[
const Text('Created Product:'),
Text(_product.toString(), style: const TextStyle(fontWeight: FontWeight.bold)),
const SizedBox(height: 20),
],
ElevatedButton(
onPressed: _createObjects,
child: const Text('Create Objects Dynamically'),
),
],
),
),
);
}
}