Flutter状态管理之state-management
2019-10-10 本文已影响0人
王俏
StatelessWidget
class StateManagementDemo extends StatelessWidget {
int count = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('StateManagementDemo'),
elevation: 0.0,
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
count++;
print(count);//打印每次按一次会加1
},
),
body: Center(
child: Chip(
label: Text('$count'),//始终显示0
),
),
);
}
}
state传递InheritedWidget
import 'package:flutter/material.dart';
class StateManagementDemo extends StatefulWidget {
@override
_StateManagementDemoState createState() => _StateManagementDemoState();
}
class _StateManagementDemoState extends State<StateManagementDemo> {
int count = 0;
void _increaseCount() {
setState(() {
count++;
});
print(count);
}
@override
Widget build(BuildContext context) {
return CounterProvider(
count: count,
increaseCount: _increaseCount,
child: Scaffold(
appBar: AppBar(
title: Text('StateManagementDemo'),
elevation: 0.0,
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: _increaseCount,
),
body: StateWrapper(),
),
);
}
}
//从父辈继承state,本身不管理state
class StateWrapper extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return Counter();
}
}
//从父辈继承state,本身不管理state
class Counter extends StatelessWidget {
@override
Widget build(BuildContext context) {
final int count = CounterProvider.of(context).count;
final VoidCallback _increaseCount = CounterProvider.of(context).increaseCount;
// TODO: implement build
return Center(
child: ActionChip(
label: Text('$count'),
onPressed: _increaseCount,
),
);
}
}
class CounterProvider extends InheritedWidget {
final int count;
final VoidCallback increaseCount;
final Widget child;
CounterProvider({this.count, this.increaseCount, this.child})
: super(child: child);
static CounterProvider of(BuildContext context) =>
context.inheritFromWidgetOfExactType(CounterProvider);
@override
bool updateShouldNotify(InheritedWidget oldWidget) {
// TODO: implement updateShouldNotify
return true;
}
}