【问题标题】:How to custom appbar style inside SearchDelegate如何在 SearchDelegate 中自定义 appbar 样式
【发布时间】:2020-05-03 13:15:21
【问题描述】:

我使用新类 extends SearchDelegate 创建了一个搜索功能。我想自定义 appBar background colorfont size。如何做到这一点?

我的搜索类

import 'package:flutter/material.dart';

class Search extends SearchDelegate {
  final List countryList;

  Search(this.countryList);

  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
        icon: Icon(Icons.clear),
        onPressed: () {
          query = '';
        },
      )
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      icon: Icon(Icons.arrow_back_ios),
      onPressed: () {
        Navigator.pop(context);
      },
    );
  }

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

  @override
  Widget buildSuggestions(BuildContext context) {
    final suggestionList = query.isEmpty
        ? countryList
        : countryList
            .where((element) =>
                element['country'].toString().toLowerCase().startsWith(query))
            .toList();

    return ListView.builder(
      itemCount: suggestionList.length,
      itemBuilder: (context, index) {
        return Card(
          child: Container(
            height: 70,
            margin: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
            child: Row(
              children: <Widget>[
                Container(
                  width: 200,
                  margin: EdgeInsets.symmetric(horizontal: 10),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Text(
                        suggestionList[index]['country'],
                        style: TextStyle(fontWeight: FontWeight.bold),
                      ),
                      Image.network(
                        suggestionList[index]['countryInfo']['flag'],
                        height: 50,
                        width: 60,
                      ),
                    ],
                  ),
                ),
                Expanded(
                    child: Container(
                  child: Column(
                    children: <Widget>[
                      Text(
                        'CONFIRMED:' +
                            suggestionList[index]['cases'].toString(),
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          color: Colors.red,
                        ),
                      ),
                      Text(
                        'ACTIVE:' + suggestionList[index]['active'].toString(),
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          color: Colors.blue,
                        ),
                      ),
                      Text(
                        'RECOVERED:' +
                            suggestionList[index]['recovered'].toString(),
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          color: Colors.green,
                        ),
                      ),
                      Text(
                        'DEATHS:' + suggestionList[index]['deaths'].toString(),
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          color: Theme.of(context).brightness == Brightness.dark
                              ? Colors.grey[100]
                              : Colors.grey[900],
                        ),
                      ),
                    ],
                  ),
                ))
              ],
            ),
          ),
        );
      },
    );
  }
}

这个类创建一个这样的应用栏

当我尝试改变背景颜色时

ThemeData appBarTheme(BuildContext context) {
  return ThemeData(
    primaryColor: Color(0xff202c3b),
  );
}

背景颜色改变了,但一些样式也改变了

我想自定义一点样式

  • 字体大小bigger
  • 字体颜色to white
  • 不要使用underline

如何做到这一点?我找不到任何TextStyle 或类似的东西

已编辑

CountryPage 类用于搜索

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

import 'package:tgd_covid_tracker/pages/search.dart';

class CountryPage extends StatefulWidget {
  @override
  _CountryPageState createState() => _CountryPageState();
}

class _CountryPageState extends State<CountryPage> {
  List countryData;

  fetchCountryData() async {
    if (this.mounted) {
      http.Response response =
          await http.get('https://corona.lmao.ninja/v2/countries');
      setState(() {
        countryData = json.decode(response.body);
      });
    }
  }

  @override
  void initState() {
    fetchCountryData();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        actions: <Widget>[
          countryData == null
              ? Container()
              : searchButton(
                  context,
                  countryData,
                ),
        ],
        title: Text('Country Stats'),
      ),
      body: countryData == null
          ? Center(
              child: CircularProgressIndicator(),
            )
          : ListView.builder(
              itemBuilder: (context, index) {
                return Card(
                  child: Container(
                    height: 70,
                    margin: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                    child: Row(
                      children: <Widget>[
                        Container(
                          width: 200,
                          margin: EdgeInsets.symmetric(horizontal: 10),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              Text(
                                countryData[index]['country'],
                                style: TextStyle(fontWeight: FontWeight.bold),
                              ),
                              Image.network(
                                countryData[index]['countryInfo']['flag'],
                                height: 50,
                                width: 60,
                              ),
                            ],
                          ),
                        ),
                        Expanded(
                          child: Container(
                            child: Column(
                              children: <Widget>[
                                Text(
                                  'CONFIRMED:' +
                                      countryData[index]['cases'].toString(),
                                  style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    color: Colors.red,
                                  ),
                                ),
                                Text(
                                  'ACTIVE:' +
                                      countryData[index]['active'].toString(),
                                  style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    color: Colors.blue,
                                  ),
                                ),
                                Text(
                                  'RECOVERED:' +
                                      countryData[index]['recovered']
                                          .toString(),
                                  style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    color: Colors.green,
                                  ),
                                ),
                                Text(
                                  'DEATHS:' +
                                      countryData[index]['deaths'].toString(),
                                  style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    color: Theme.of(context).brightness ==
                                            Brightness.dark
                                        ? Colors.grey[100]
                                        : Colors.grey[900],
                                  ),
                                ),
                              ],
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                );
              },
              itemCount: countryData == null ? 0 : countryData.length,
            ),
    );
  }
}

Widget searchButton(BuildContext context, countryData) {
  return IconButton(
    icon: Icon(Icons.search),
    onPressed: () {
      showSearch(context: context, delegate: Search(countryData));
    },
  );
}

【问题讨论】:

  • 请告诉我们您在代码中的何处实现了 appbar 样式?
  • 你在哪里实现了搜索栏@Bertho Joris,请添加代码
  • 好的,我会更新我的代码
  • 嗨@Adnankarim 检查我的更新
  • 嗨 @RandomGuru 检查我的更新

标签: flutter dart


【解决方案1】:

以下工作完美无缺:

class CustomSearchDelegate extends SearchDelegate {
  @override
  ThemeData appBarTheme(BuildContext context) {
    return ThemeData(
      textTheme: TextTheme(
        // Use this to change the query's text style
        headline6: TextStyle(fontSize: 24.0, color: Colors.white),
      ),
      appBarTheme: const AppBarTheme(
        backgroundColor: Colors.green,
      ),
      inputDecorationTheme: InputDecorationTheme(
        border: InputBorder.none,
        
        // Use this change the placeholder's text style
        hintStyle: TextStyle(fontSize: 24.0),
      ),
    );
  }
}

【讨论】:

    【解决方案2】:

    您可以像这样为标题提供样式:

    title: Text("MyApp", style:TextStyle(color:Colors.black,fontWeight:FontWeight.w300,fontSize:20)
    

    并为下划线添加以下属性

    decoration:TextDecoration.none
    

    您必须在 AppBar() 属性中添加它。

    最后:

    title: Text("MyApp", 
      style:TextStyle(
        color:Colors.black,
        fontWeight:FontWeight.w300,
        fontSize:20,
        decoration:TextDecoration.none
      )
    

    【讨论】:

    • @BerthoJoris 在你的 AppBar()中
    • 我申请了CountryPage 课程,但是当我按下搜索并显示搜索字段时,并没有改变任何东西。还是一样
    • 抱歉,SearchDelegate 的样式来自应用的主题。我以为你在讨论 AppBar(),一种方法是调整主题,但这不会改变太多的属性
    • 是的...这就是我的意思。必须在 appBarTheme 里面对吧?有什么建议吗?
    【解决方案3】:

    我了解这个问题,我的解决方案无法解决整个问题,但如果您只是更改 appBarTheme 的一些属性,您可以使用 .copyWith 方法并指明哪些属性是你想覆盖。

    @override
      ThemeData appBarTheme(BuildContext context) {
        // TODO: implement appBarTheme
        return super.appBarTheme(context).copyWith(//OVERRIDE PROPERTIES HERE);
      }
    

    【讨论】:

      【解决方案4】:

      您可以像这样覆盖您的 appBarTheme:

      @override
        ThemeData appBarTheme(BuildContext context) {
          assert(context != null);
          final ThemeData theme = Theme.of(context).copyWith(
            appBarTheme: AppBarTheme(
              color: Colors.black, //new AppBar color
              elevation: 0,
            ),
            textTheme: TextTheme(
              headline6: TextStyle(
                color: Colors.white,
              ),
            ),
          );
        }
      

      【讨论】:

        【解决方案5】:

        您可以使用 SearchDelegate 类中的 appBarTheme 方法来更改 AppBar 主题。 (https://api.flutter.dev/flutter/material/SearchDelegate-class.html)

        例子:

        // Default App Theme
        
        @override
        ThemeData appBarTheme(BuildContext context) {
          return Theme.of(context);
        }
        
        // Changing AppBar color only for current AppBar
        
        @override
        ThemeData appBarTheme(BuildContext context) {
          return Theme.of(context).copyWith(
            appBarTheme: Theme.of(context).appBarTheme.copyWith(
                  color: const Color(0xff202c3b),
                ),
          );
        }
        

        【讨论】:

          猜你喜欢
          • 2021-06-05
          • 1970-01-01
          • 2019-05-08
          • 2021-02-23
          • 2019-05-28
          • 2018-07-15
          • 1970-01-01
          • 1970-01-01
          • 2019-07-30
          相关资源
          最近更新 更多