Flutter之ChangeNotifier学习

Flutter之ChangeNotifier学习,第1张

Flutter之ChangeNotifier学习 最简单的使用 上代码
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.orange,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

class Counter extends ChangeNotifier {
  // 这里也可以使用with来进行实现
  int _count = 0; //数值计算
  int get count => _count;

  addCount() {
    _count++;
    notifyListeners();
  }
}

Counter _counter = Counter();

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
  @override
  void initState() {
    super.initState();
    _counter.addListener(() {
      // 数值改变的监听
      print('YM--->新数值:${_counter.count}');
    });
  }

  @override
  void dispose() {
    super.dispose();
    _counter.dispose(); //移除监听
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Hello')),
      body: Center(
        child: Container(
          child: RaisedButton(onPressed: () {
            _counter.addCount();
          }, child: Text('计数'),),
        ),
      ),
    );
  }
}
创建一个继承ChangeNotifier的类
class Counter extends ChangeNotifier {
  // 这里也可以使用with来进行实现
  int _count = 0; //数值计算
  int get count => _count;

  addCount() {
    _count++;
    notifyListeners();
  }
}
在外边创建一个持久化的对象

Counter _counter = Counter();

在initState的时候注册Listener
  @override
  void initState() {
    super.initState();
    _counter.addListener(() {
      // 数值改变的监听
      print('YM--->新数值:${_counter.count}');
    });
  }
dispose的时候dispose掉,然后就不能用了
  @override
  void dispose() {
    super.dispose();
    _counter.dispose(); //移除监听,再调用的话会崩溃
  }
调用_counter.addCount();
_counter.addCount(); // 里面调用了notifyListeners()方法

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5708350.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存