Flutter 使用provider进行全局状态管理
1. 导入provider
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
provider: ^6.0.2
2. 创建一个provider
本篇创建一个AppProvider全局状态管理类,里面管理一个int类型的变量progress。
import 'package:flutter/material.dart';
class AppProvider extends ChangeNotifier {
int? progress = 1;
int? getProgress() {
return progress;
}
void setProgress(int? progress) {
this.progress = progress;
notifyListeners();
}
}
- 在main.dart中注册
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_provider/provider/app_provider.dart';
void main() {
runApp(
MultiProvider(
// 接受监听
providers: [
ChangeNotifierProvider.value(value: AppProvider()),
],
child: const MyApp(),
),
);
}
- 创建一个home_page.dart的页面 ,里面包含两个组件progress1和progress2,在两个组件中通过改变全局的progress值来显示组件
值得注意的是,在build里面获取全局状态的值,必须用watch。在initState中可以用read
home_page.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_provider/provider/app_provider.dart';
import 'package:test_provider/views/src/progress1.dart';
import 'package:test_provider/views/src/progress2.dart';
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
"测试",
)),
body: Stack(
children: [
_createBottomView(),
],
));
}
_createBottomView() {
var progress = context.watch<AppProvider>().getProgress();
if (progress == 1) {
return Progress1();
} else {
return Progress2();
}
}
}
progress1.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_provider/provider/app_provider.dart';
class Progress1 extends StatefulWidget {
const Progress1({Key? key}) : super(key: key);
@override
State<Progress1> createState() => _Progress1State();
}
class _Progress1State extends State<Progress1> {
@override
Widget build(BuildContext context) {
return Positioned(
bottom: 0,
left: 0,
right: 0,
child: Column(
children: [
const Text("这是步骤1"),
MaterialButton(
color: Colors.blue,
textColor: Colors.white,
child: const Text('前往下一步'),
onPressed: () {
var app = context.read<AppProvider>();
app.setProgress(2);
},
)
],
));
}
}
progress2.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../provider/app_provider.dart';
class Progress2 extends StatefulWidget {
const Progress2({Key? key}) : super(key: key);
@override
State<Progress2> createState() => _Progress1State();
}
class _Progress1State extends State<Progress2> {
@override
Widget build(BuildContext context) {
return Positioned(
bottom: 0,
left: 0,
right: 0,
child: Column(
children: [
const Text("这是步骤2"),
MaterialButton(
color: Colors.blue,
textColor: Colors.white,
child: const Text('退回第一步'),
onPressed: () {
var app = context.read<AppProvider>();
app.setProgress(1);
},
)
],
));
}
}