Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Searchdelegate, i want to add background color and appbar color when i click the search

Tags:

flutter

i can change my background color and app bar in home just fine, but when i click the search icon which uses search delegate it all back to white, how do i change the color? just to make it clear, so before the user clicked the search icon the background and app bar was black but when they clicked it it turned to white, how do i change it?

here is the search code :

import 'package:flutter/material.dart';
import 'package:movie_app_3/model/movie_response.dart';
import 'package:movie_app_3/screens/movie_detail_screen/movie_detail_screen.dart';

import '../model/movie.dart';
import '../repository/repository.dart';

class DataSearch extends SearchDelegate {
  // void initState() {
  //   searchBloc..getSearch(query);
  // }
  final movieRepo = MovieRepository();
  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
        icon: Icon(Icons.clear),
        onPressed: () => query = '',
      )
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      icon: AnimatedIcon(
          icon: AnimatedIcons.menu_arrow, progress: transitionAnimation),
      onPressed: () => close(context, null),
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    return Container();
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    if (query.isEmpty) return Container();

    return FutureBuilder<MovieResponse>(
      future: movieRepo.getSearch(query),
      builder: (BuildContext context, AsyncSnapshot<MovieResponse> snapshot) {
        if (snapshot.hasData) {
          if (snapshot.data.error != null && snapshot.data.error.length > 0) {
            return _buildErrorWidget(snapshot.data.error);
          }
          return _buildHomeWidget(snapshot.data);
        } else if (snapshot.hasError) {
          return _buildErrorWidget(snapshot.error);
        } else {
          return _buildLoadingWidget();
        }
      },
    );
  }

  Widget _buildHomeWidget(MovieResponse data) {
    List<Movie> movies = data.movies;
    return ListView.builder(
      itemCount: movies.length,
      itemBuilder: (context, index) {
        return ListTile(
          leading: FadeInImage(
              image: movies[index].poster == null
                  ? AssetImage('assets/images/no-image.jpg')
                  : NetworkImage("https://image.tmdb.org/t/p/w200/" +
                      movies[index].poster),
              placeholder: AssetImage('assets/images/no-image.jpg'),
              width: 50.0,
              fit: BoxFit.contain),
          title: Text(
            movies[index].title,
            style: TextStyle(fontFamily: 'Poppins'),
          ),
          subtitle: Text(
            movies[index].overview,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(fontFamily: 'Raleway'),
          ),
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => MovieDetailScreen(movie: movies[index]),
              ),
            );
          },
        );
      },
    );
  }

  Widget _buildLoadingWidget() {
    return Center(
        child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        SizedBox(
          height: 25.0,
          width: 25.0,
          child: CircularProgressIndicator(
            valueColor: new AlwaysStoppedAnimation<Color>(Colors.black),
            strokeWidth: 4.0,
          ),
        )
      ],
    ));
  }

  Widget _buildErrorWidget(String error) {
    return Center(
        child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text("Error occured: $error"),
      ],
    ));
  }
  // @override
  // Widget buildSuggestions(BuildContext context) {
  //   final suggestedList = (query.isEmpty) ?
  //                         recentMovies :
  //                         movies.where((movie) => movie.toLowerCase().contains(query.toLowerCase())).toList();

  //   return ListView.builder(
  //     itemCount: suggestedList.length,
  //     itemBuilder: (context, i) {
  //       return ListTile(
  //         leading: Icon(Icons.movie),
  //         title: Text(suggestedList[i]),
  //         onTap: () {},
  //       );
  //     },
  //   );
  // }

}

here is the home code :

import 'package:flutter/material.dart';

import 'package:movie_app_3/widget/drawer.dart';
import 'package:movie_app_3/screens/home_screen/widget/home_screen1.dart';
import 'package:movie_app_3/screens/home_screen/widget/home_screen2.dart';
import 'package:movie_app_3/widget/search.dart';

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen>
    with SingleTickerProviderStateMixin {
  TabController _tabController;
  @override
  void initState() {
    super.initState();
    _tabController = TabController(vsync: this, length: 2);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            Colors.black,
            Color(0xff112339),
            Colors.black,
          ],
        ),
      ),
      child: DefaultTabController(
        length: 2,
        child: Scaffold(
          backgroundColor: Colors.transparent,
          appBar: AppBar(
            elevation: 0,
            title: Text(
              'Moviez',
              style: TextStyle(
                fontSize: 24,
                color: Colors.white,
                fontFamily: 'Poppins',
              ),
            ),
            backgroundColor: Colors.transparent,
            centerTitle: true,
            actions: [
              Padding(
                padding: EdgeInsets.only(right: 20),
                child: IconButton(
                  icon: Icon(Icons.search),
                  onPressed: () {
                    showSearch(context: context, delegate: DataSearch());
                  },
                ),
              ),
            ],
            bottom: TabBar(
              controller: _tabController,
              indicatorColor: Colors.white,
              indicatorSize: TabBarIndicatorSize.tab,
              indicatorWeight: 2.0,
              tabs: [
                Padding(
                  padding: const EdgeInsets.symmetric(vertical: 8.0),
                  child: Text(
                    'Discover',
                    style: TextStyle(fontSize: 16, fontFamily: 'Raleway'),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.symmetric(vertical: 8.0),
                  child: Text(
                    'Genres',
                    style: TextStyle(fontSize: 16, fontFamily: 'Raleway'),
                  ),
                ),
              ],
            ),
          ),
          drawer: MyDrawer(),
          body: TabBarView(
            controller: _tabController,
            children: <Widget>[
              FirstTab(),
              SecondTab(),
            ],
          ),
        ),
      ),
    );
  }
}
like image 570
Wonderweis Avatar asked Oct 21 '25 13:10

Wonderweis


2 Answers

Add this to your "DataSearch" class

class _SearchDelegate extends SearchDelegate {

  @override
  ThemeData appBarTheme(BuildContext context) {
    return Theme.of(context).copyWith(
      scaffoldBackgroundColor: Colors.green,
    );
  }
like image 149
Levent KANTAROGLU Avatar answered Oct 23 '25 02:10

Levent KANTAROGLU


For customizing the Search Delegate, you have to override a method called appBarTheme and then set your custom theme on that.

** NOTE: When you override appBarTheme of SearchDelegate you have to customize evrything related to SearchBar yourself. Just like the code below. **

Do this to change the AppBar Color:

@override
ThemeData appBarTheme(BuildContext context) {
   return ThemeData(
   appBarTheme: const AppBarTheme(
    color: MyColors.mainColor, // affects AppBar's background color
    hintColor: Colors.grey, // affects the initial 'Search' text
    textTheme: const TextTheme(
      headline6: TextStyle( // headline 6 affects the query text
          color: Colors.white,
          fontSize: 16.0,
          fontWeight: FontWeight.bold)),
   ),
  );   
}

And for changing the background color of suggestions:

@override
Widget buildSuggestions(BuildContext context) {

  return Container(
     color: Colors.black,
     ...
  );
}

Similarly do this for results:

@override
Widget buildResults(BuildContext context) {
  
  return Container(
     color: Colors.black,
     ...
  );
}

Hope this helps.

like image 33
Rehan Dev Avatar answered Oct 23 '25 03:10

Rehan Dev