import 'package:flutter/foundation.dart';
class TestNotifierController extends ChangeNotifier {
String _value = '0';
String get value => _value;
set value(String newValue) {
if (_value == newValue) return;
_value = newValue;
notifyListeners();
}
}
import 'package:flutter/widgets.dart';
import 'package:provider_demo/test_notifier_controller.dart';
class TestNotifierWidget extends StatefulWidget {
const TestNotifierWidget({
Key? key,
this.controller,
}) : super(key: key);
final TestNotifierController? controller;
@override
_TestNotifierWidgetState createState() => _TestNotifierWidgetState();
}
class _TestNotifierWidgetState extends State<TestNotifierWidget> {
@override
void initState() {
super.initState();
widget.controller?.addListener(_change);
}
@override
void dispose() {
widget.controller?.removeListener(_change);
super.dispose();
}
@override
Widget build(BuildContext context) {
return Text(widget.controller?.value ?? '初始值');
}
void _change() {
if (mounted) setState(() {});
}
}
import 'package:flutter/material.dart';
import 'package:provider_demo/test_notifier_controller.dart';
import 'package:provider_demo/test_notifier_widget.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final controller = TestNotifierController();
var count = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Column(
children: [
TestNotifierWidget(
controller: controller,
),
MaterialButton(
onPressed: () {
controller.value = '${++count}';
},
child: const Text('点击增加'),
),
],
),
);
}
}