context.dependOnInheritedWidgetOfExactType返回null的问题

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的使用问题,原因暂时不清楚。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值