ChangeNotifier單獨使用舉例

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('點擊增加'),
          ),
        ],
      ),
    );
  }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容