【自学Flutter】25 InheritedWidget数据共享的使用
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int counter = 0;
void _incrementCounter() {
setState(() {
counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
CounterText(), // 使用 CounterText Widget
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
class CounterText extends StatelessWidget {
@override
Widget build(BuildContext context) {
// 使用 InheritedWidget 中的共享数据
return Text(
'${context.dependOnInheritedWidgetOfExactType<CounterInheritedWidget>().data}',
style: Theme.of(context).textTheme.headline4,
);
}
}
class CounterInheritedWidget extends InheritedWidget {
final int data;
CounterInheritedWidget({
Key key,
@required this.data,
@required Widget child,
}) : super(key: key, child: child);
// 确定是否需要重新构建 Widget
@override
bool updateShouldNotify(CounterInheritedWidget oldWidget) => data != oldWidget.data;
}
在这个代码示例中,我们创建了一个CounterInheritedWidget
类,它继承自InheritedWidget
并包含一个整数数据。在_MyHomePageState
的build
方法中,我们使用CounterInheritedWidget
来包裹需要共享数据的子Widget。CounterText
Widget通过dependOnInheritedWidgetOfExactType
方法获取共享的数据并显示。这样,我们就可以在不同的Widget树层级间共享数据,而不需要通过构造函数或者任何回调函数来传递数据。
评论已关闭