Flutter 3.X Provider最简用法
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
main() {
runApp(
const MyApp(),
);
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MultiProvider(
//创建顶层共享数据
providers: [
ChangeNotifierProvider(create: (_) => Counter()),
],
child: const MaterialApp(
debugShowCheckedModeBanner:false,
title: "Provider示例",
home: FirstPage(),
));
}
}
class FirstPage extends StatelessWidget {
const FirstPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('这是第一页'),
actions: <Widget>[
OutlinedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.green),
foregroundColor: MaterialStateProperty.all(Colors.white)
),
child: const Text("下一页",),
onPressed: () => Navigator.push(
context,
MaterialPageRoute(builder: (context) {
return const SecondPage();
}),
),
),
],
),
body: Center(
//在子页面中获取状态 Provider.of<T>(context).xx
child: Text("${Provider.of<Counter>(context).count}"),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Provider.of<Counter>(context,listen: false).increment(); //listen: false必须写否则报错
},
child: const Icon(Icons.add),
),
);
}
}
class SecondPage extends StatelessWidget {
const SecondPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('这是第二页'),
),
body: Center(
child: Text("${Provider.of<Counter>(context).count}"),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Provider.of<Counter>(context,listen: false).increment();
},
child: const Icon(Icons.add),
),
);
}
}
//定义数据model
class Counter with ChangeNotifier {
//混入ChangeNotifier,自动管理所有听众
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners(); //通知所有听众刷新
}
}