Flutter:我应该如何使用 InheritedWidget?
Posted
技术标签:
【中文标题】Flutter:我应该如何使用 InheritedWidget?【英文标题】:Flutter: How Should I Use an InheritedWidget? 【发布时间】:2020-07-25 23:22:53 【问题描述】:简介:我认为这个问题原则上可能是共享的,但我觉得这个具体的应用程序不是。我谦虚地提交它以供考虑,所以请温柔。我的代码在这里偶然发现了一个明显的陷阱,我根本不知道如何修复它。考虑了几个小时后,我什至不知道该怎么做。
问题:InheritedWidget 没有更新其上方小部件的状态。
期望:我希望当我在 HomePage 的 PageView 上滑动时,Text BottomAppBar 将更新。但是,这不会发生。
描述:我正在尝试使用一个 InheritedWidget (InheritedPageIndex),它是在根小部件 (MaterialApp) via 一个 Provider 方法(请参阅下面的代码)。其中,有一个值会向下传递到小部件树中它下方的小部件 (MenuPage)。我希望这个值在状态改变时更新;我尝试通过在小部件树中它下方的小部件中滑动 PageView (HomePage) 来进行修改。
代码:我已经重写并简化了我的代码,以便我们可以更轻松地诊断和解决问题,它看起来像这样:
page_index_model.dart
import 'package:flutter/material.dart';
class PageIndex
PageIndex(@required this.index);
double index = 0;
page_index_provider.dart
import 'package:flutter/cupertino.dart';
import 'package:testinginheritedwidget/models/page_index_model.dart';
class InheritedPageIndex extends InheritedWidget
InheritedPageIndex(Key key, @required this.indexData, Widget child)
: super(key: key, child: child);
final PageIndex indexData;
@override
bool updateShouldNotify(InheritedWidget oldWidget) => true;
static PageIndex of(BuildContext context) => context
.dependOnInheritedWidgetOfExactType<InheritedPageIndex>()
.indexData;
main.dart
import 'package:flutter/material.dart';
import 'package:testinginheritedwidget/models/page_index_model.dart';
import 'package:testinginheritedwidget/pages/menu_page.dart';
import 'package:testinginheritedwidget/providers/page_index_provider.dart';
void main() => runApp(App());
class App extends StatelessWidget
@override
Widget build(BuildContext context)
return InheritedPageIndex(
indexData: PageIndex(index: 0),
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Testing Inherited Widgets',
home: MenuPage(),
),
);
menu_page.dart
import 'package:flutter/material.dart';
import 'package:testinginheritedwidget/models/page_index_model.dart';
import 'package:testinginheritedwidget/pages/home_page.dart';
import 'package:testinginheritedwidget/providers/page_index_provider.dart';
class MenuPage extends StatelessWidget
@override
Widget build(BuildContext context)
PageIndex _pageIndex = InheritedPageIndex.of(context);
return DefaultTabController(
length: 3,
child: Scaffold(
//TODO: dot indicator
resizeToAvoidBottomInset: false,
appBar: AppBar(
backgroundColor: Colors.black,
title: Center(
child: Text('Testing Inherited Widgets',
style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold)),
),
bottom: TabBar(
onTap: (tabIndex) ,
labelColor: Colors.white,
indicatorColor: Colors.white,
tabs: const <Widget>[
Tab(icon: Icon(Icons.flight), child: Text('Flight')),
Tab(icon: Icon(Icons.map), child: Text('Map')),
Tab(icon: Icon(Icons.print), child: Text('Print')),
],
),
),
body: SafeArea(
child: TabBarView(
children: <Widget>[
HomePage(),
HomePage(),
HomePage(),
],
),
),
bottomNavigationBar: BottomAppBar(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
// *** PROBLEM 1 IS HERE ***
Text('$_pageIndex.index'),
],
),
),
),
);
home_page.dart
import 'package:flutter/material.dart';
import 'package:testinginheritedwidget/models/page_index_model.dart';
import 'package:testinginheritedwidget/providers/page_index_provider.dart';
class HomePage extends StatefulWidget
@override
_HomePageState createState() => _HomePageState();
class _HomePageState extends State<HomePage>
List<Widget> cards = [];
@override
Widget build(BuildContext context)
PageIndex _pageIndex = InheritedPageIndex.of(context);
for (var index = 0; index < 7; index++)
cards.add(
Center(
child: Text(
'$index',
style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
),
),
);
print(index);
return PageView(
onPageChanged: (index)
setState(()
//*** PROBLEM 2 IS HERE ***
_pageIndex.index = index.toDouble();
print('page index: $_pageIndex.index');
);
,
children: cards,
);
假设:经过大量研究和反思。我相信我无法更新 Provider 的价值;因为它在第一个实例化的 InheritedWidget 和改变状态的方法之间。也许另一种说法是,我想改变的状态就在它的正上方;并且,它取而代之的是第二个提供者的状态,而不是使用第一个?
问题:
1)为了我的利益,我的假设是正确的,还是这里发生了其他事情?
2) 如何解决我的问题?我不认为实现 BLoC 方法可以解决这个问题,因为它也使用了提供程序?
在这种情况下,如果没有 InheritedWidget,我不知道如何将状态向上传递到小部件树。
【问题讨论】:
您好 George,这个问题对于使用提供者来说很简单,这是无法实现的,因为您必须将提供的提供者值更改为 true,但这会导致再次构建小部件。我建议将 rxdart 与流生成器一起用于需要显示标题的底行。然后在更改页面时使用数据更新发布者主题。这样代码会更干净,更易于管理pub.dev/packages/rxdart 【参考方案1】:你根本不需要一个包。一个有点hacky的方法是在inheritedWidget周围创建一个Wrapper,因为继承的小部件不会自行重建,您需要在有状态的小部件中使用它。
class MyWrapper extends StatefulWidget
const MyWrapper(this.child);
final Widget child;
@override
_MyWrapperState createState() => _MyWrapperState();
class _MyWrapperState extends State<MyWrapper>
int index = 0;
changePageIndex(int newIndex)
setState(()
index = newIndex;
);
@override
Widget build(BuildContext context)
return InheritedPageIndex(indexData: index , child: widget.child, state: this);
class InheritedPageIndex extends InheritedWidget
InheritedPageIndex(
Key key, @required this.indexData, @required this.state, Widget child)
: super(key: key, child: child);
final _MyWrapperState state;
final int indexData;
@override
bool updateShouldNotify(InheritedPageIndex oldWidget) =>
indexData != oldWidget.indexData;
static InheritedPageIndex of(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<InheritedPageIndex>();
那就这样用吧
MyWrapper(
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Testing Inherited Widgets',
home: MenuPage(),
),
);
最后像这样访问/更改它
int indexData = InheritedPageIndex.of(context).indexData; //we access the variable
InheritedPageIndex.of(context).state.changePageIndex(1); //We change it, and all the widgets that accessed the data with InheritedPageIndex.of(context).indexData rebuild themselves
【讨论】:
【参考方案2】:包解决方案
简介:为了彻底起见,我已将代码作为使用 Provider 包的最终答案包含在内,如上面的 cmets 中所建议的那样。如您所料,此代码比上面不使用包的答案更简单。
代码:
main.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:***questionthree/counter_model.dart';
import 'package:***questionthree/page_menu.dart';
void main() => runApp(App());
class App extends StatelessWidget
@override
Widget build(BuildContext context)
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Testing Inherited Widgets',
home: ChangeNotifierProvider(
create: (BuildContext context) => Counter(0),
child: MenuPage(),
),
);
counter_model.dart
import 'package:flutter/material.dart';
class Counter with ChangeNotifier
int _counter;
Counter(this._counter);
getCounter() => _counter;
setCounter(int counter) => _counter = counter;
void increment(int counter)
_counter = counter;
notifyListeners();
page_menu.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:***questionthree/counter_model.dart';
import 'package:***questionthree/home_page.dart';
class MenuPage extends StatefulWidget
@override
_MenuPageState createState() => _MenuPageState();
class _MenuPageState extends State<MenuPage>
var _bloc;
@override
Widget build(BuildContext context)
final counter = Provider.of<Counter>(context);
return DefaultTabController(
length: 3,
child: Scaffold(
//TODO: dot indicator
resizeToAvoidBottomInset: false,
appBar: AppBar(
backgroundColor: Colors.black,
title: Center(
child: Text('Testing Inherited Widgets',
style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold)),
),
bottom: TabBar(
onTap: (tabIndex)
counter.increment(0);
,
labelColor: Colors.white,
indicatorColor: Colors.white,
tabs: const <Widget>[
Tab(icon: Icon(Icons.flight), child: Text('Flight')),
Tab(icon: Icon(Icons.map), child: Text('Map')),
Tab(icon: Icon(Icons.print), child: Text('Print')),
],
),
),
body: SafeArea(
child: TabBarView(
children: <Widget>[
HomePage(),
HomePage(),
HomePage(),
],
),
),
bottomNavigationBar: BottomAppBar(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
//TODO: insert value below.
Text(counter.getCounter().toString()),
],
),
),
),
);
home_page.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:***questionthree/counter_model.dart';
class HomePage extends StatefulWidget
@override
_HomePageState createState() => _HomePageState();
class _HomePageState extends State<HomePage>
List<Widget> cards = [];
@override
Widget build(BuildContext context)
final counter = Provider.of<Counter>(context);
for (var index = 0; index < 7; index++)
cards.add(
Center(
child: Text(
'$index',
style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
),
),
);
print(index);
return PageView(
onPageChanged: (index)
setState(()
counter.increment(index);
);
,
children: cards,
);
【讨论】:
【参考方案3】:您应该检查这个包:https://pub.dev/packages/provider,它是 InheritedWidget 的包装器。并检查ChangeNotiferProvider,它公开了ChangeNotifier
类,并允许在更新时通知侦听器。如果您需要更多解释,我随时待命
【讨论】:
以上是关于Flutter:我应该如何使用 InheritedWidget?的主要内容,如果未能解决你的问题,请参考以下文章