Flutter:我应该如何使用 InheritedWidget?
Flutter: How Should I Use an InheritedWidget?
简介:我认为这个问题原则上是可以共享的,但我觉得这个具体应用不是。我谦虚地提交考虑,所以请温柔。我在这里用我的代码偶然发现了一个明显的陷阱,我根本不知道如何修复它。想了好几个小时,我都不知道该怎么办。
问题: InheritedWidget 没有更新其上方小部件中的状态。
期望: 我希望当我在 HomePage 的 PageView 上滑动时,BottomAppBar 的 Text 将更新。然而,这并没有发生。
描述: 我正在尝试使用 InheritedWidget (InheritedPageIndex),我在根小部件 (MaterialApp) via 上方初始化 Provider 方法(请参阅下面的代码)。其中,有一个值传递给小部件树中它下面的小部件 (MenuPage)。我希望这个值在状态改变时更新;我尝试通过在 Widget 树中它下面的 widget 中滑动 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,
);
}
}
假设:经过大量研究和思考。我相信我无法更新提供者的价值;因为它位于第一个实例化的 InheritedWidget 和更改状态的方法之间。也许另一种说法是,我要更改的状态就在它的正上方;并且,它取而代之的是第二个提供者的状态,而不是使用第一个提供者的状态?
问题:
1)为了我的利益,我的假设是否正确,还是这里发生了其他事情?
2) 我该如何解决我的问题?我不相信实施 BLoC 方法会解决这个问题,因为它也是使用提供商?
在这种情况下,如果没有 InheritedWidget,我不知道如何将状态向上传递到小部件树。
你应该检查这个包:https://pub.dev/packages/provider which is wrappers of InheritedWidget. And check the ChangeNotiferProvider 它公开了一个 ChangeNotifier
class 并允许在更新时通知听众。如果您需要更多解释,我有空
包解决方案
简介: 为了完整起见,我将代码作为使用 Provider 包的最终答案,如上面评论中所建议的那样。如您所料,这段代码比上面不使用包的答案更简单。
代码:
main.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:Whosebugquestionthree/counter_model.dart';
import 'package:Whosebugquestionthree/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:Whosebugquestionthree/counter_model.dart';
import 'package:Whosebugquestionthree/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:Whosebugquestionthree/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,
);
}
}
你根本不需要这个包。一个有点老套的方法是围绕继承的小部件创建一个包装器,因为继承的小部件不会自行重建,您需要在有状态的小部件中使用它。
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
简介:我认为这个问题原则上是可以共享的,但我觉得这个具体应用不是。我谦虚地提交考虑,所以请温柔。我在这里用我的代码偶然发现了一个明显的陷阱,我根本不知道如何修复它。想了好几个小时,我都不知道该怎么办。
问题: InheritedWidget 没有更新其上方小部件中的状态。
期望: 我希望当我在 HomePage 的 PageView 上滑动时,BottomAppBar 的 Text 将更新。然而,这并没有发生。
描述: 我正在尝试使用 InheritedWidget (InheritedPageIndex),我在根小部件 (MaterialApp) via 上方初始化 Provider 方法(请参阅下面的代码)。其中,有一个值传递给小部件树中它下面的小部件 (MenuPage)。我希望这个值在状态改变时更新;我尝试通过在 Widget 树中它下面的 widget 中滑动 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,
);
}
}
假设:经过大量研究和思考。我相信我无法更新提供者的价值;因为它位于第一个实例化的 InheritedWidget 和更改状态的方法之间。也许另一种说法是,我要更改的状态就在它的正上方;并且,它取而代之的是第二个提供者的状态,而不是使用第一个提供者的状态?
问题:
1)为了我的利益,我的假设是否正确,还是这里发生了其他事情?
2) 我该如何解决我的问题?我不相信实施 BLoC 方法会解决这个问题,因为它也是使用提供商?
在这种情况下,如果没有 InheritedWidget,我不知道如何将状态向上传递到小部件树。
你应该检查这个包:https://pub.dev/packages/provider which is wrappers of InheritedWidget. And check the ChangeNotiferProvider 它公开了一个 ChangeNotifier
class 并允许在更新时通知听众。如果您需要更多解释,我有空
包解决方案
简介: 为了完整起见,我将代码作为使用 Provider 包的最终答案,如上面评论中所建议的那样。如您所料,这段代码比上面不使用包的答案更简单。
代码:
main.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:Whosebugquestionthree/counter_model.dart';
import 'package:Whosebugquestionthree/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:Whosebugquestionthree/counter_model.dart';
import 'package:Whosebugquestionthree/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:Whosebugquestionthree/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,
);
}
}
你根本不需要这个包。一个有点老套的方法是围绕继承的小部件创建一个包装器,因为继承的小部件不会自行重建,您需要在有状态的小部件中使用它。
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