Flutter开发:如何在Home.dart添加搜索栏并避免双AppBar
Hey there! Let's tackle your problem step by step. The double AppBar issue happens because MenuUsers.dart already provides the parent Scaffold with an AppBar, so adding another one in Home.dart creates a nested bar. Instead, we'll add the search bar directly to the existing AppBar in MenuUsers.dart (right next to the sign-out button) and adjust Home.dart to avoid nested scaffolds.
Step 1: Modify MenuUsers.dart to Add the Search Bar
We'll integrate a search field into the existing AppBar and pass the search query to the Home widget so it can filter results.
Updated MenuUsers.dart Code Snippet
class _MenuUsersState extends State<MenuUsers> { String name = ""; String _searchQuery = ""; // Add state variable for search input // ... your existing getPref(), signOut() methods ... @override Widget build(BuildContext context) { return DefaultTabController( length: 4, child: Scaffold( appBar: AppBar( backgroundColor: Colors.pink, // Add search bar as AppBar's title title: Container( height: 40, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(20), ), child: TextField( decoration: InputDecoration( hintText: "Search attractions...", prefixIcon: Icon(Icons.search, color: Colors.pink), border: InputBorder.none, contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 8), ), onChanged: (value) { setState(() { _searchQuery = value; }); }, ), ), actions: <Widget>[ IconButton( onPressed: (){ signOut(); }, icon: Icon(Icons.lock_open), ) ], ), body: TabBarView( children: <Widget>[ // Pass search query to Home widget Home(searchQuery: _searchQuery), Budget(), LocationMap(), Profile(), ], ), // ... your existing bottomNavigationBar ... ), ); } }
Step 2: Adjust Home.dart to Avoid Nested Scaffolds & Add Search Filtering
Since MenuUsers already provides the parent scaffold, we can remove the Scaffold wrapper in Home.dart and add logic to filter results based on the search query.
Updated Home.dart Code Snippets
- Update StatefulWidget to accept search query:
class Home extends StatefulWidget { final String searchQuery; // Constructor to receive search query from MenuUsers Home({required this.searchQuery}); @override _HomeState createState() => _HomeState(); }
- Add filtered list getter and update build method:
class _HomeState extends State<Home> { var loading = false; List<CategoryProductModel> listCategory = []; List<UserAttractionModel> list =[]; // ... your existing getProductWithCategory(), getAttraction(), onRefrash() methods ... // Get filtered list based on search query List<UserAttractionModel> get _filteredAttractions { if (widget.searchQuery.isEmpty) return list; return list.where((attraction) => attraction.attractionName.toLowerCase().contains(widget.searchQuery.toLowerCase()) ).toList(); } @override Widget build(BuildContext context) { // Remove redundant Scaffold wrapper return loading ? Center( child: CircularProgressIndicator(), ) : RefreshIndicator( onRefresh: onRefrash, child: ListView( children: <Widget>[ // ... your existing category list ... filter ? // ... your existing category-based grid ... : GridView.builder( shrinkWrap: true, physics: ClampingScrollPhysics(), padding: EdgeInsets.all(10), // Use filtered list for search results itemCount: _filteredAttractions.length, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, mainAxisSpacing: 15, crossAxisSpacing: 8 ), itemBuilder: (context,i){ final a = _filteredAttractions[i]; return InkWell( onTap: () { Navigator.push(context, MaterialPageRoute( builder: (context) => ProductDetail(a))); }, // ... your existing attraction card UI ... ); } ), ], ), ); } }
Key Changes Explained
- No more double AppBar: We removed the redundant
ScaffoldinHome.dartsince the parentMenuUsersalready manages the main scaffold and app bar. - Search bar placement: The search field is integrated directly into the existing
AppBarinMenuUsers.dart, positioned left of the sign-out button. - Search functionality: The search query is passed to
Home.dartwhere we filter the attraction list in real-time as the user types.
You can extend this further by adding search filtering for category-specific results too—just apply the same logic to the category-based grid.
内容的提问来源于stack exchange,提问作者MissAnon

