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'),
),
);
}
}