Flutter _ 状态管理探索篇——Scoped Model
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(
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ScopedModel<CounterModel>(
model: CounterModel(),
child: CounterHome(),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => Navigator.of(context).push(MaterialPageRoute(builder: (context) => CounterPage())),
child: Icon(Icons.add),
),
);
}
}
class CounterHome extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
ScopedModelDescendant<CounterModel>(
builder: (context, child, model) {
return Text(
'${model.count}',
style: Theme.of(context).textTheme.display1,
);
},
),
],
);
}
}
class CounterPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ScopedModelDescendant<CounterModel>(
builder: (context, child, model) {
return Text(
'You have pushed the button this many times: ${model.count}',
);
},
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => ScopedModel.of<CounterModel>(context).increment(),
child: Icon(Icons.add),
),
);
}
}
class CounterModel extends Model {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}
这段代码使用了Scoped Model来管理状态,在HomePage和CounterPage页面中展示了计数器的当前值,并且在CounterPage中有一个按钮可以增加计数器的值。这个例子展示了如何使用Scoped Model来简化状态管理,并且提供了一个清晰的状态共享模式。
评论已关闭