Flutter中学习InheritedWidget组件时,按照教程的写法,首先定义Widget继承InheritedWidget如下:
class DataWidget extends InheritedWidget {
String data1;
DataWidget({super.key,required Widget child, this.data1="初始数据"}):super(child: child);
static DataWidget? of(BuildContext context){
return context.dependOnInheritedWidgetOfExactType<DataWidget>();
}
@override
bool updateShouldNotify(covariant InheritedWidget oldWidget) {
return true;
}
}
使用如下:
class InheritedTestPage extends StatefulWidget {
const InheritedTestPage({Key? key}) : super(key: key);
@override
State<StatefulWidget> createState() {
// TODO: implement createState
return _InheritedTestState();
}
}
class _InheritedTestState extends State<StatefulWidget> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("InheritedTest 的测试工作"),
),
body: DataWidget(
data1: "这个数据是共享的",
child: Column(
children: [
SizedBox(
height: 10,
),
Text("你好呀"),
Text(DataWidget.of(context)==null?"没获取到数据":DataWidget.of(context)!.data1),
],
)),
);
}
}
结果: 页面上的数据一致是没获取到数据,
DataWidget.of(context)的返回值为null。
解决方法:
import 'package:flutter/material.dart';
import 'package:flutter_app/widget/data_widget.dart';
class InheritedTestPage extends StatefulWidget {
const InheritedTestPage({Key? key}) : super(key: key);
@override
State<StatefulWidget> createState() {
// TODO: implement createState
return _InheritedTestState();
}
}
class _InheritedTestState extends State<StatefulWidget> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("InheritedTest 的测试工作"),
),
body: DataWidget(
data1: "这个数据是共享的",
child: Builder(
builder: (BuildContext innerContext) {
return Column(
children: [
SizedBox(
height: 10,
),
Text("你好呀"),
Text(DataWidget.of(innerContext) == null
? "没获取到数据"
: DataWidget.of(innerContext)!.data1),
],
);
},
)));
}
}
使用的context的使用问题,原因暂时不清楚。