flutter_provider_demo

This commit is contained in:
2025-02-17 21:26:52 +08:00
commit 68259775e7
135 changed files with 5653 additions and 0 deletions

View File

@ -0,0 +1,101 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class SelectorPage extends StatelessWidget {
const SelectorPage({super.key});
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (_) => ComplexState(),
child: Scaffold(
appBar: AppBar(
title: const Text('Selector Example'),
),
body: const Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CountSelector(),
NameSelector(),
UpdateButtons(),
],
),
),
),
);
}
}
class ComplexState extends ChangeNotifier {
int _count = 0;
String _name = "John";
int get count => _count;
String get name => _name;
void incrementCount() {
_count++;
notifyListeners();
}
void changeName() {
_name = _name == "John" ? "Jane" : "John";
notifyListeners();
}
}
class CountSelector extends StatelessWidget {
const CountSelector({super.key});
@override
Widget build(BuildContext context) {
return Selector<ComplexState, int>(
selector: (_, state) => state.count,
builder: (context, count, child) {
print('Count rebuild');
return Text('Count: $count');
},
);
}
}
class NameSelector extends StatelessWidget {
const NameSelector({super.key});
@override
Widget build(BuildContext context) {
return Selector<ComplexState, String>(
selector: (_, state) => state.name,
builder: (context, name, child) {
print('Name rebuild');
return Text('Name: $name');
},
);
}
}
class UpdateButtons extends StatelessWidget {
const UpdateButtons({super.key});
@override
Widget build(BuildContext context) {
return Column(
children: [
ElevatedButton(
onPressed: () {
context.read<ComplexState>().incrementCount();
context.read<ComplexState>().changeName();
},
child: const Text('Increment Count'),
),
ElevatedButton(
onPressed: () {
context.read<ComplexState>().changeName();
},
child: const Text('Change Name'),
),
],
);
}
}