Skip to content

Instantly share code, notes, and snippets.

@ReinRaus
Last active October 19, 2023 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ReinRaus/50e340da1ea3c75f0aa66a32394db32d to your computer and use it in GitHub Desktop.
Save ReinRaus/50e340da1ea3c75f0aa66a32394db32d to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: ChangeNotifierProvider<MyState>(
create: (context) => MyState(),
child: const Body(),
),
),
);
}
}
class MyState with ChangeNotifier {
List<int> values = [0, 0, 0];
void increment(int key) {
values[key]++;
notifyListeners();
}
}
class Body extends StatelessWidget {
const Body({super.key});
@override
Widget build(BuildContext context) {
var values = context.watch<MyState>().values;
return Column(
children: [
Row(
children: [
for (int i = 0; i < values.length; i++)
Selector<MyState, int>(
selector: (_, state) {
print("Selector index: $i, selector: ${state.values[i]}");
return state.values[i];
},
shouldRebuild: (previous, next) {
print(
"Should index: $i, prev: $previous, next: $next ${previous != next ? ", NEED REBUILD" : ""}");
return previous != next;
},
builder: (_, __, ___) {
print("Build index: $i");
return Expanded(
child: Center(
child: Text(
"${values[i]}",
textScaleFactor: 3,
)));
},
)
],
),
Row(
children: [
for (int i = 0; i < values.length; i++)
Expanded(
child: Center(
child: TextButton(
onPressed: () {
print("-" * 20);
print("Increment index: $i");
context.read<MyState>().increment(i);
},
child: Text("Increment $i"),
),
),
)
],
),
Center(
child: Text(
"Summ: ${values.reduce((value, element) => value + element)}",
textScaleFactor: 2,
),
),
],
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment