这里我们使用的是官方提供的provider
链接地址:https://pub.flutter-io.cn/packages/provider
接下来使用一个简单的例子,实现两个组件之间值的同时改变
provider类的代码
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class Counter with ChangeNotifier {
int _count = 0;
int get count => _count;
intCount() {
_count++;
notifyListeners();
}
}
在根组件外面嵌套一个组件MultiProvider
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => Counter()),
//如果有多个provider则在这里按上面的方法再写
],
child: ......,
);
}
}
·两个组件里面的代码:
Cart.dart
import 'package:flutter/material.dart';
import 'package:flutterjdshop/provider/Counter.dart';
import 'package:provider/provider.dart';
class CartPage extends StatefulWidget {
CartPage({Key? key}) : super(key: key);
@override
State<CartPage> createState() => _CartPageState();
}
class _CartPageState extends State<CartPage> {
@override
Widget build(BuildContext context) {
var counterProvider = Provider.of<Counter>(context);
return Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () {
counterProvider.intCount();
},
child: Icon(Icons.add),
),
body: Center(
child: Text("${counterProvider.count}"),
),
);
}
}
USer.dart
import 'package:flutter/material.dart';
import 'package:flutterjdshop/provider/Counter.dart';
import 'package:provider/provider.dart';
class UserPage extends StatefulWidget {
UserPage({Key? key}) : super(key: key);
@override
State<UserPage> createState() => _UserPageState();
}
class _UserPageState extends State<UserPage> {
@override
Widget build(BuildContext context) {
var counterProvider = Provider.of<Counter>(context);
return Center(
child: Text("${counterProvider.count}"),
);
}
}
当点击加号时,购物车页面数字递增时,我的页面内数字也会跟着增大。平时我们要页面发生改变时会使用setState来让build方法重新执行让界面重新加载,这里我们不用setState,provider中notifyListeners();方法的调用也会让界面重新加载,两个页面都是从provider中获取值渲染在页面上。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)