import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), useMaterial3: true, ), home: const MyHomePage(), ); } } abstract class ListStrategy { List compose(List items); } class Monkey { Monkey({required this.name, required this.power}); final String name; final int power; @override String toString() => '$name - Power: $power'; } class GreatestMonkeyStrategy implements ListStrategy { @override List compose(List items) { return [ items.fold( Monkey(name: '', power: 0), (aMonkey, bMonkey) => aMonkey.power > bMonkey.power ? aMonkey : bMonkey) ]; } } class WeakMonkeysStrategy implements ListStrategy { @override List compose(List items) { return items .where( (element) => element.power <= 200, ) .toList(); } } List monkeys = [ Monkey(name: 'Mortimer', power: 25), Monkey(name: 'ApeMan', power: 354), Monkey(name: 'Spider', power: 65), Monkey(name: 'DK', power: 500), Monkey(name: 'Tim', power: 120), Monkey(name: 'Kong', power: 25400), ]; class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State createState() => _MyHomePageState(); } class _MyHomePageState extends State { ListStrategy listStrat = WeakMonkeysStrategy(); void swapStrategies() { if (listStrat.runtimeType == WeakMonkeysStrategy) { setState(() => listStrat = GreatestMonkeyStrategy()); return; } setState(() => listStrat = WeakMonkeysStrategy()); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).colorScheme.inversePrimary, title: const Text('Abstract Factory'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text('All monkeys:'), ...monkeys .map( (e) => Text(e.toString()), ) .toList(), const SizedBox(height: 50), Text(listStrat.runtimeType.toString()), ...listStrat .compose(monkeys) .map( (e) => Text(e.toString()), ) .toList(), const SizedBox(height: 100), ElevatedButton(onPressed: () => swapStrategies(), child: const Text('Change Strats')), ], ), ), ); } }