Created
August 25, 2024 18:48
-
-
Save yousefak007/12ad1255892a02da1a10970fced17b56 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'; | |
import 'package:watch_it/watch_it.dart'; | |
void main() { | |
runApp( | |
const MyApp(), | |
); | |
} | |
class Counter with ChangeNotifier { | |
int _count = 0; | |
int get count => _count; | |
void increment() { | |
_count++; | |
notifyListeners(); | |
} | |
} | |
class MyApp extends StatelessWidget { | |
const MyApp({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
return const MaterialApp( | |
home: MyHomePage(), | |
); | |
} | |
} | |
class WatchItBuilder extends StatelessWidget with WatchItMixin { | |
const WatchItBuilder({ | |
super.key, | |
required this.builder, | |
}); | |
final WidgetBuilder builder; | |
@override | |
Widget build(BuildContext context) => builder(context); | |
} | |
class MyHomePage extends StatelessWidget { | |
const MyHomePage({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
return Column( | |
children: [ | |
Expanded( | |
child: WatchItBuilder( | |
builder: (context) { | |
pushScope(init: (getIt) { | |
getIt.registerSingleton<Counter>(Counter()); | |
}); | |
return const Page( | |
title: 'Page 1', | |
); | |
}, | |
), | |
), | |
Expanded( | |
child: WatchItBuilder( | |
builder: (context) { | |
pushScope(init: (getIt) { | |
getIt.registerSingleton<Counter>(Counter()); | |
}); | |
return const Page( | |
title: 'Page 2', | |
); | |
}, | |
), | |
), | |
], | |
); | |
} | |
} | |
class Page extends StatelessWidget { | |
final String title; | |
const Page({super.key, required this.title}); | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text(title), | |
), | |
body: const Center( | |
child: Column( | |
mainAxisSize: MainAxisSize.min, | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
Text('You have pushed the button this many times:'), | |
Count(), | |
], | |
), | |
), | |
floatingActionButton: FloatingActionButton( | |
onPressed: () => di<Counter>().increment(), | |
child: const Icon(Icons.add), | |
), | |
); | |
} | |
} | |
class Count extends StatelessWidget with WatchItMixin { | |
const Count({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
final counter = watchIt<Counter>(); | |
return Text( | |
'${counter.count}', | |
style: Theme.of(context).textTheme.headlineMedium, | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment