flutter 单例
flutter中的单例
class DataSave{
factory DataSave() => shared();
static DataSave _instance;
DataSave._() {
}
static DataSave shared(){
if(_instance == null){
_instance = DataSave._();
}
return _instance;
}
//添加一个属性 通过单例来缓存属性值
var a = 0;
}
使用
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
//赋值并存储在单利中
DataSave.shared().a = 200;
return MaterialApp(
title: '单例测试',
home: Scaffold(
appBar: AppBar(title: Text('data'),),
body: TestPage(),
),
);
}
}
class TestPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
//读取单例的值
int a = DataSave.shared().a;
return Scaffold(
body: Center(
child: Text('$a'),
),
);
}
}