Flutter单例演示

2022年9月17日 711点热度 0人点赞 0条评论

界面效果
Flutter单例演示插图

<code>class Manager{
  //单例变量
  static Manager? _instance;

  //命名构造函数
  Manager._internal(){
    //初始化
  }

  //创建实例
  static Manager _getInstance(){
    _instance ??= Manager._internal();
    return _instance!;
  }

  //无参构造函数也是从_getInstance()获得实例
  factory Manager() =&gt; _getInstance();

  //对外暴露获取实例接口
  static Manager get instance =&gt; _getInstance();
}
</code>

界面:

<code>import &#039;package:app_bili/factory_singleton_instance.dart&#039;;
import &#039;package:flutter/material.dart&#039;;

main()=&gt;runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text(&quot;Factory&quot;),
          centerTitle: true,
        ),
        body: const MyHomePage()
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();
}

class _MyHomePageState extends State&lt;MyHomePage&gt; {

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ElevatedButton(
          onPressed: (){
            Manager manager1 = Manager();
            Manager? manager2 = Manager.instance;
            Manager manager3 = Manager();
            print(identical(manager1, manager2)); //true
            print(identical(manager1, manager3)); //true
          },
          child: const Text(&quot;点击&quot;)
      ),
    );
  }
}</code>

小小调酒师

此刻打盹,你将做梦; 此刻学习,你将圆梦。 个人邮箱:shellways@foxmail.com

文章评论