首先让我向您展示如何使用您的方法解决此问题的示例 - 请同时阅读代码块中的 cmets - 这些应该有助于更好地理解我在那里所做的!
剧透:我们不想在 Flutter 中这样做,因为它会导致到处传递对象/函数,并且很难维护这样的代码 - 有很好的解决方案对于“状态管理”下总结的这个“问题”。
我创建了一个类,用于保存在搜索栏中输入的当前搜索查询:
class SearchModel {
String searchString = '';
}
然后我们有我们的简约视图,我们在其中使用 Scaffold 小部件和(就像在您的示例中一样)AppBar 和 ListView:
class HomeView extends StatefulWidget {
@override
_HomeViewState createState() => _HomeViewState();
}
class _HomeViewState extends State<HomeView> {
SearchModel _searchModel = SearchModel();
_updateSearch(String searchQuery) {
/// The setState function is provided by StatefulWidget, every Widget we
/// create which extends StatefulWidget has access to this function. By calling
/// this function we essentially say Flutter we want the Widget (which is coupled
/// with this state of this StatefulWidget) that we want to rebuild (call the build
/// function again)
setState(() {
_searchModel.searchString = searchQuery;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: PreferredSize(
/// We pass down the _updateSearch function to our AppBar so when the user
/// changes the text in the TextField it will update the searchString in our
/// SearchModel object and call setState so we rebuild HomeViewState (which is
/// currently the root of our app, so everything gets rebuilded)
child: MyAppBar(
searchFunction: _updateSearch,
),
preferredSize: Size.fromHeight(kToolbarHeight)),
/// In MyListView, where we use the ListView internally to show the results, we
/// just pass down our SearchModel object where the searchString is maintained
/// so we can filter our list
body: MyListView(
searchModel: _searchModel,
),
);
}
}
现在是我们的 AppBar,用户可以在其中输入内容并搜索我们的列表:
class MyAppBar extends StatefulWidget {
/// This is how we declare a function type in Dart where we say which
/// kind of parameters (here String) it will use
final Function(String) searchFunction;
MyAppBar({this.searchFunction});
@override
_MyAppBarState createState() => _MyAppBarState();
}
class _MyAppBarState extends State<MyAppBar> {
@override
Widget build(BuildContext context) {
return AppBar(
title: TextField(
/// onChanged of TextField needs a function where we pass down
/// a String and do what we want, thats what the searchFunction is for!
onChanged: widget.searchFunction,
),
);
}
}
最后但并非最不重要的是 ListView 小部件,我们在其中显示一些元素,如果用户更改了 AppBar 的 TextField 中的输入,我们希望过滤这些元素并仅显示与 searchQuery 匹配的元素:
class MyListView extends StatefulWidget {
final SearchModel searchModel;
MyListView({this.searchModel});
@override
_MyListViewState createState() => _MyListViewState();
}
class _MyListViewState extends State<MyListView> {
List<String> games = [
'Anno 1602',
'Final Fantasy 7',
'Final Fantasy 8',
'Dark Souls'
];
@override
Widget build(BuildContext context) {
return ListView(
/// Some minimalistic usage of functions which are usable on List objects:
/// I initialised a random List of game names as Strings and the first thing
/// I want to do is to filter out all the games which contain the same String
/// pattern like the searchQuery which the user entered - this is done with the
/// where function. The where function returns the filtered list, on this filtered
/// list i use the map function, which takes every object from this list and "maps"
/// it to whatever we want, here for every game String I want a ListTile Widget which
/// is being used for our ListView! At the end I have to call toList() since those
/// functions return so called Iterables instead of List object, "basically" the same
/// but different classes so we just change the Iterables to List
children: games
.where((game) => game
.toLowerCase()
.contains(widget.searchModel.searchString.toLowerCase()))
.map(
(game) => ListTile(
title: Text(game),
),
)
.toList(),
);
}
}
这行得通,但是正如我在开头所说的那样,这样做会迫使您将对象/函数传递给每个 Widget 字面上的任何地方!一旦你的应用程序变得足够大,你的所有小部件都会有几十个参数,你很快就会忘记你在哪里做了什么,维护、改进、扩展你的代码几乎是不可能的。
这就是为什么我们需要一种叫做状态管理的东西!尽管 Flutter 相当新,至少与其他知名框架相比,社区为状态管理提出了许多不同的解决方案/方法。您应该自己阅读以找出最适合您的解决方案 - 实际上很大程度上取决于个人喜好。由于我个人喜欢并使用 Provider(您可以单独使用它作为解决方案)和 MobX 一起使用,我将向您展示如何仅使用 Provider (https://pub.dev/packages/provider) 来处理此示例:
首先是我们的 SearchModel,现在它得到了扩展:
/// We extend our classes which are basically our "States" with ChangeNotifier
/// so we enable our class to notify all listeners about a change - you will see
/// why!
class SearchModel extends ChangeNotifier {
String searchString = '';
/// Now we don't update the searchString variable directly anymore, we use a
/// function because we need to call notifiyListeners every time we change something
/// where we want to notify everyone and all the listeners can react to this change!
updateSearchString(searchQuery) {
this.searchString = searchQuery;
notifyListeners();
}
}
现在我们的新 AppBar:
/// Our own Widgets MyAppBar and MyListView are not Stateless! We don't need the state
/// anymore (at least in this example) since we won't use setState anymore and tell
/// our Widgets to rebuild, but will make use of a Widget provided by the Provider
/// package which will rebuild itself dynamically! More later in MyListView
class MyAppBar extends StatelessWidget {
@override
Widget build(BuildContext context) {
return AppBar(
title: TextField(
/// context.watch is also a function added through the Provider package where
/// we can access objects which have been provided by a Provider Widget (you
/// will see this in the HomeView implementation) and thats how we now pass
/// the function instead of passing it down to this Widget manually! Easier right?
onChanged: context.watch<SearchModel>().updateSearchString,
),
);
}
}
更新后的 ListView:
class MyListView extends StatelessWidget {
final List<String> games = [
'Anno 1602',
'Final Fantasy 7',
'Final Fantasy 8',
'Dark Souls'
];
@override
Widget build(BuildContext context) {
return ListView(
/// Just like in the MyAppBar implementation we can access our SearchModel object
/// directly by using context.watch instead of passing it down to our Widget!
/// again: very nice
/// The function itself hasn't been changed!
/// Since we are using the watch function on a object which extends ChangeNotifier,
/// every time it gets updated, this will get rebuilded automatically! Magic
children: games
.where((game) => game.toLowerCase().contains(
context.watch<SearchModel>().searchString.toLowerCase()))
.map(
(game) => ListTile(
title: Text(game),
),
)
.toList(),
);
}
}
现在我们的 HomeView 基本上是这个视图的开始:
/// Every Widget we created manually now is stateless since we don't manage any
/// state by ourself now, which reduces the boilerplate and makes accessing stuff easier!
/// Whats left: in our MyListView and MyAppBar Widgets we accessed the SearchModel
/// object with context.watch ... but how is this possible? Well, we need to provide
/// it somehow of course - thats where the Provider packages gets handy again!
class HomeView extends StatelessWidget {
@override
Widget build(BuildContext context) {
/// The Provider package has several Provider Widgets, one is the ChangeNotifierProvider
/// which can be used to provide objects which extend ChangeNotifier, just what we need!
///
/// Some background: we have to remember that Flutter is basically a big tree. Usually we
/// use a MaterialApp Widget as the root Widget and after that everything else is being
/// passed down as a child which will result in a big tree. What we do here: As early as we
/// need it / want to we place our Provider Widget and "pass down" our Model which should be
/// accessible for every Widget down the tree. Every Widget which is now under this Provider
/// (in our case MyAppBar and MyListView) can access this object with context.watch and
/// work with it
return ChangeNotifierProvider(
create: (_) => SearchModel(),
builder: (context, _) => Scaffold(
appBar: PreferredSize(
child: MyAppBar(), preferredSize: Size.fromHeight(kToolbarHeight)),
body: MyListView(),
),
);
}
}
需要阅读很多内容 - 很抱歉写了这么长,但我想确保向您展示问题,尝试您的方法如何解决它,以及为什么尽早学习和使用 Flutter 中的状态管理如此重要尽可能!我希望这能让您深入了解它为什么重要和好的原因,并且它使 Flutter 更加出色。
我在此示例中使用 Provider 的方式也只是使用此状态管理解决方案的众多方式之一 - 我强烈建议您自己在我之前链接的 Provider 本身的 pub.dev 站点上阅读它。有很多示例如何以及何时使用 Provider 的不同 Widgets/方法!
希望对您有所帮助! :)