import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
class CounterService {
int count = 0;
void increment() {
count++;
}
}
final getIt = GetIt.instance;
void setupLocator() {
getIt.registerSingleton<CounterService>(CounterService());
}
void main() {
setupLocator();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: CounterScreen(),
);
}
}
class CounterScreen extends StatefulWidget {
const CounterScreen({super.key});
@override
State<CounterScreen> createState() => _CounterScreenState();
}
class _CounterScreenState extends State<CounterScreen> {
final CounterService counterService = getIt<CounterService>();
void _incrementCounter() {
setState(() {
counterService.increment();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Simple Counter')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Count: ${counterService.count}', style: const TextStyle(fontSize: 24)),
const SizedBox(height: 20),
ElevatedButton(
onPressed: _incrementCounter,
child: const Text('Increment'),
),
],
),
),
);
}
}
We created a CounterService class that holds the count and an increment method. We use GetIt to register this service as a singleton in setupLocator(). In the _CounterScreenState, we get the instance of CounterService from GetIt. The UI shows the current count from the service. When the button is pressed, we call increment() on the service and call setState to update the UI. This way, the business logic is separated from the UI and injected cleanly.