Related
I'm getting this error called The named parameter 'key' is required, but there's no corresponding argument. I'm developing a simple BMI calculator app using flutter, android studio. didn't understand about the error I'm new to flutter. can anyone tell me what to do about this error? followed up this youtube video and the code is here github.
import 'package:bmi_cal/constants/app_constants.dart';
import 'package:bmi_cal/widgets/left_bar.dart';
import 'package:bmi_cal/widgets/right_bar.dart';
import 'package:flutter/material.dart';
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
TextEditingController _heightController = TextEditingController();
TextEditingController _weightController = TextEditingController();
double _bmiResult = 0;
String _textResult = "";
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
"BMI Calculator",
style:
TextStyle(color: accentHexColor, fontWeight: FontWeight.w300),
),
backgroundColor: Colors.transparent,
elevation: 0,
centerTitle: true,
),
backgroundColor: mainHexColor,
body: SingleChildScrollView(
child: Column(
children: [
SizedBox(
height: 20,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
width: 130,
child: TextField(
controller: _heightController,
style: TextStyle(
fontSize: 42,
fontWeight: FontWeight.w300,
color: accentHexColor),
keyboardType: TextInputType.number,
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Height",
hintStyle: TextStyle(
fontSize: 42,
fontWeight: FontWeight.w300,
color: Colors.white.withOpacity(.8)),
),
),
),
Container(
width: 130,
child: TextField(
controller: _weightController,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 42,
fontWeight: FontWeight.w300,
color: accentHexColor),
keyboardType: TextInputType.number,
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Weight",
hintStyle: TextStyle(
fontSize: 42,
fontWeight: FontWeight.w300,
color: Colors.white.withOpacity(.8)),
),
),
),
],
),
SizedBox(
height: 30,
),
GestureDetector(
onTap: () {
double _h = double.parse(_heightController.text);
double _w = double.parse(_weightController.text);
setState(() {
_bmiResult = _w / (_h * _h);
if(_bmiResult > 25){
_textResult = "You\'re over weight";
} else if(_bmiResult >= 18.5 && _bmiResult <= 25){
_textResult = "You have normal weight";
}else{
_textResult = "You\'re under weight";
}
});
},
child: Container(
child: Text(
"Calculate",
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.bold,
color: accentHexColor),
),
),
),
SizedBox(
height: 50,
),
Container(
child: Text(
_bmiResult.toStringAsFixed(2),
style: TextStyle(fontSize: 90, color: accentHexColor),
),
),
SizedBox(
height: 30,
),
Visibility(
visible: _textResult.isNotEmpty,
child: Container(
child: Text(
_textResult,
style: TextStyle(
fontSize: 32,
fontWeight: FontWeight.w400,
color: accentHexColor),
),
)),
SizedBox(height: 10,),
LeftBar(barWidth: 40,),
SizedBox(height: 20,),
LeftBar(barWidth: 70),
SizedBox(height: 20,),
LeftBar(barWidth: 40,),
SizedBox(height: 20,),
RightBar(barWidth: 70),
SizedBox(height: 50,),
RightBar(barWidth: 70),
],
),
));
}
}
main.dart
import 'package:bmi_cal/screens/home.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'BMI calculator',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.yellow,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: HomeScreen(),
);
}
}
This error normally indicates, that the widget you are trying to add to the widget tree does have a constructor similar to the following:
const LeftBar({required Key key, #required this.barWidth}) : super(key: key);
The error seems to be related to the first required argument with the name key. Just remove the required keyword, since it the key is mostly needed for testing the widget and should be optional.
I checked your source code on github and I dont think it is up to date for this example.
enter image description here
You have to just try this:
Add "VoidCallback" instead of "Function" onpress.
Remove # sign
Add required keyword
for detail see the below picture
enter image description here
I would like to create a home page for my flutter app. I used templates from the network, but unfortunately I don't get it the way I sketched it in the picture. maybe someone can help me with that
sketch / result
Unfortunately, I'm sure that I can't do it better: - /, would like to have it exactly like the one on the left (icons and colors are not so important)
I used this link from the forum as a template for the appbar, and I had difficulties in inserting it ^^
Custom AppBar Flutter
I also got the code for the BottomNavigationBar from somewhere in the forum, but I think this is not suitable for my purposes anyway. Since I don't like this shrink effect when clicking on it, the two arrow buttons at the edge should snap back when pressed and not stay in the pressed state, as they should stand for the front and back function ...
here is my complete main.dart
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
themeMode: ThemeMode.light,
theme: ThemeData(
primaryColor: Color(0xFF34445c),
primaryColorBrightness: Brightness.light,
brightness: Brightness.light,
primaryColorDark: Colors.black,
canvasColor: Color(0xFFCECECE),
appBarTheme: AppBarTheme(brightness: Brightness.light)),
darkTheme: ThemeData(
primaryColor: Colors.black,
primaryColorBrightness: Brightness.dark,
primaryColorLight: Colors.black,
brightness: Brightness.dark,
primaryColorDark: Colors.black,
indicatorColor: Colors.white,
canvasColor: Colors.black,
appBarTheme: AppBarTheme(brightness: Brightness.dark)),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final _selectedItemColor = Colors.white;
final _unselectedItemColor = Colors.white30;
final _selectedBgColor = Color(0xFF293749);
final _unselectedBgColor = Color(0xFF34445c);
int _selectedIndex = 0;
static const TextStyle optionStyle =
TextStyle(fontSize: 15, fontWeight: FontWeight.normal);
static const List<Widget> _widgetOptions = <Widget>[
Text(
'Index 0: ZURÜCK',
style: optionStyle,
),
Text(
'Index 1: FAVORITES',
style: optionStyle,
),
Text(
'Index 2: KOMMENTARE / LÖSCHEN',
style: optionStyle,
),
Text(
'Index 3: ABOUT-US',
style: optionStyle,
),
Text(
'Index 4: WEITER',
style: optionStyle,
),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
Color _getBgColor(int index) =>
_selectedIndex == index ? _selectedBgColor : _unselectedBgColor;
Color _getItemColor(int index) =>
_selectedIndex == index ? _selectedItemColor : _unselectedItemColor;
Widget _buildIcon(IconData iconData, String text, int index) => Container(
width: double.infinity,
height: kBottomNavigationBarHeight,
child: Material(
color: _getBgColor(index),
child: InkWell(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(iconData),
Text(text,
style: TextStyle(fontSize: 9, color: _getItemColor(index))),
],
),
onTap: () => _onItemTapped(index),
),
),
);
_appBar(height) => PreferredSize(
preferredSize: Size(MediaQuery.of(context).size.width, height+80 ),
child: Stack(
children: <Widget>[
Container(
child: Center(
child: Text("TEXT", style: TextStyle(fontSize: 15.0,
fontWeight: FontWeight.w600,
color: Colors.white),
),
),
color:Theme.of(context).primaryColor,
height: height+75,
width: MediaQuery.of(context).size.width,
),
Container(
),
Positioned( // To take AppBar Size only
top: 100.0,
left: 20.0,
right: 20.0,
child: AppBar(
backgroundColor: Color(0xFF293749),
leading: Icon(Icons.menu, color: Colors.white),
primary: false,
title: Container(
margin: EdgeInsets.only(top: 4.0, bottom: 4.0, right: 0.0, left: 0.0),
color: Colors.white,
child: Container(
margin: EdgeInsets.only(top: 0.0, bottom: 0.0, right: 5.0, left: 5.0),
child: TextField(
decoration: InputDecoration(
hintText: "Suchen",
border: InputBorder.none,
hintStyle: TextStyle(color: Colors.grey))),
),
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.search, color: Colors.white), onPressed: () {},),
],
),
)
],
),
);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: _appBar(AppBar().preferredSize.height),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
selectedFontSize: 0,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: _buildIcon(Icons.arrow_back_ios_rounded, 'ZURÜCK', 0),
title: SizedBox.shrink(),
),
BottomNavigationBarItem(
icon: _buildIcon(Icons.favorite, 'FAVORITEN', 1),
title: SizedBox.shrink(),
),
BottomNavigationBarItem(
icon: _buildIcon(Icons.comment, 'KOMMENTARE', 2),
title: SizedBox.shrink(),
),
BottomNavigationBarItem(
icon: _buildIcon(Icons.info_outline_rounded, 'ÜBER UNS', 3),
title: SizedBox.shrink(),
),
BottomNavigationBarItem(
icon: _buildIcon(Icons.arrow_forward_ios_rounded, 'WEITER', 4),
title: SizedBox.shrink(),
),
],
currentIndex: _selectedIndex,
selectedItemColor: _selectedItemColor,
unselectedItemColor: _unselectedItemColor,
),
);
}
}
I have modified your code with some commentaries to support you in building the UI.
For the AppBar, you are going in the right direction of using PreferredSize with Stack, just some minor adjustments.
For the BottomNavigationBar, since the provided BottomNavigationBarItem has the icon and title attributes already, we can use that and modify the color from their parents. The 2 arrows buttons can be placed together within the Row.
Here's the full example:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
themeMode: ThemeMode.light,
theme: ThemeData(
primaryColor: Color(0xFF34445c),
primaryColorBrightness: Brightness.light,
brightness: Brightness.light,
primaryColorDark: Colors.black,
canvasColor: Color(0xFFCECECE),
appBarTheme: AppBarTheme(brightness: Brightness.light)),
darkTheme: ThemeData(
primaryColor: Colors.black,
primaryColorBrightness: Brightness.dark,
primaryColorLight: Colors.black,
brightness: Brightness.dark,
primaryColorDark: Colors.black,
indicatorColor: Colors.white,
canvasColor: Colors.black,
appBarTheme: AppBarTheme(brightness: Brightness.dark)),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final _selectedItemColor = Colors.white;
final _unselectedItemColor = Colors.white30;
final _selectedBgColor = Color(0xFF293749);
final _unselectedBgColor = Color(0xFF34445c);
int _selectedIndex = 0;
static const TextStyle optionStyle =
TextStyle(fontSize: 15, fontWeight: FontWeight.normal);
static const List<Widget> _widgetOptions = <Widget>[
Text(
'Index 0: ZURÜCK',
style: optionStyle,
),
Text(
'Index 1: FAVORITES',
style: optionStyle,
),
Text(
'Index 2: KOMMENTARE / LÖSCHEN',
style: optionStyle,
),
Text(
'Index 3: ABOUT-US',
style: optionStyle,
),
Text(
'Index 4: WEITER',
style: optionStyle,
),
];
_appBar() => PreferredSize(
preferredSize: Size.fromHeight(300),
child: Container(
height: 300,
child: Stack(
children: <Widget>[
Container(
color: Color(0xFF34445D),
height: 180,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"APP TITLE",
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.w600,
color: Colors.white),
),
SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List<Widget>.generate(
4,
(index) => Padding(
padding: EdgeInsets.symmetric(horizontal: 8.0),
child: Icon(Icons.people, color: Colors.white), // Sample icons for demonstration
),
),
)
],
),
),
Positioned(
top: 150.0,
left: 20.0,
right: 20.0,
child: Container(
color: Color(0xFF293749),
child: Row(
children: [
IconButton(
icon: Icon(Icons.menu, size: 40, color: Colors.white),
padding: EdgeInsets.zero,
onPressed: () {},
),
Expanded(
child: Container(
margin: EdgeInsets.symmetric(vertical: 3),
padding: EdgeInsets.only(left: 3),
color: Colors.white,
height: 30,
child: TextField(
style: TextStyle(color: Colors.black, fontSize: 12),
decoration: InputDecoration(
hintText: 'Search...',
border: InputBorder.none),
),
),
),
IconButton(
icon: Icon(Icons.search, size: 30, color: Colors.white),
padding: EdgeInsets.zero,
onPressed: () {},
),
],
),
),
),
],
),
),
);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: _appBar(),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: Container(
color: _selectedBgColor,
child: Row(
children: [
IconButton(
icon: Icon(Icons.arrow_back_ios, color: Colors.white),
onPressed: () {
setState(() {
_selectedIndex =
_selectedIndex <= 0 ? _selectedIndex : _selectedIndex - 1;
});
},
),
Expanded(
child: BottomNavigationBar(
type: BottomNavigationBarType.fixed, // Add the type here to avoid auto resize
backgroundColor: _selectedBgColor, // You can also set the unselectedBackgroundColor
currentIndex: _selectedIndex,
onTap: (index) => setState(() => _selectedIndex = index), // Update the selected index
selectedItemColor: _selectedItemColor,
unselectedItemColor: _unselectedItemColor,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.favorite), title: Text('FAVORITEN')),
BottomNavigationBarItem(
icon: Icon(Icons.comment), title: Text('KOMMENTARE')),
BottomNavigationBarItem(
icon: Icon(Icons.info_outline_rounded),
title: Text('ÜBER UNS')),
],
),
),
IconButton(
icon: Icon(Icons.arrow_forward_ios, color: Colors.white),
onPressed: () {
setState(() {
_selectedIndex =
_selectedIndex >= 2 ? _selectedIndex : _selectedIndex + 1;
});
},
),
],
),
),
);
}
}
I need to add another item to my list in a flutter app. The problem comes in the children: quotes.map((quote) => quoteTemplate(quote)).toList() part. I have tried adding a text widget after it to try and test it. However, I constantly get error. The error says I cannot add list to Widgets. My full code is.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import "quote.dart";
void main() => runApp(MaterialApp(
home: QuoteList(),
));
class QuoteList extends StatefulWidget {
#override
_QuoteListState createState() => _QuoteListState();
}
class _QuoteListState extends State<QuoteList> {
int index = 1;
List <Quote> quotes = [
Quote(text: "1. It always seems impossible until it's done.", author: "Nelson Mandela", date: "1954"),
Quote(text: "2. Don't watch the clock; do what it does. Keep going.", author: "Sam Levenson", date: "1985"),
Quote(text: "3. Live life to the fullest, and focus on the positive.", author: "Matt Cameron", date: "1965"),
];
Widget quoteTemplate(quote) {
return Card(
margin: EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 0),
elevation: 5,
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
quote.text,
style: TextStyle(
fontSize: 18.0,
color: Colors.grey[600],
),
),
SizedBox(height: 17.0),
Text(
quote.author,
style: TextStyle(
fontSize: 11.0,
color: Colors.grey[700],
),
),
SizedBox(height: 17.0),
Text(
quote.date,
style: TextStyle(
fontSize: 11.0,
color: Colors.grey[750],
),
),
],
),
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
"Quote App",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
centerTitle: true,
backgroundColor: Colors.green,
),
backgroundColor: Colors.white,
body:
Center(
child: Column(
children: quotes.map((quote) => quoteTemplate(quote)).toList(),
//quotes.map((quote) => quoteTemplate(quote)).toList().toString(),
),
),
);
}
}
You can append to an existing list using the ... syntax:
Column(
children: [
...quotes.map((quote) => quoteTemplate(quote)).toList(),
Text(),
Text(),
],
),
https://flutter.dev/docs/development/ui/layout#nesting-rows-and-columns
When I was looking at the linked page above
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart' show debugPaintSizeEnabled;
void main() {
debugPaintSizeEnabled = true; // Remove to suppress visual layout
runApp(MyApp());
}
class MyApp extends StatelessWidget {
Widget stars=Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.star, color: Colors.green[500]),
Icon(Icons.star, color: Colors.green[500]),
Icon(Icons.star, color: Colors.black),
Icon(Icons.star, color: Colors.black),
Icon(Icons.star, color: Colors.black),
],
);
Widget ratings = Container(
padding: EdgeInsets.all(20),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
stars,
Text(
'130 Reviews',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w800,
fontFamily: 'Roboto',
letterSpacing: 0.5,
fontSize: 20,
),
),
],
),
);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter layout demo',
home: Scaffold(
appBar: AppBar(
title: Text('Flutter layout demo'),
),
// Change to buildColumn() for the other column example
body: ratings,
),
);
}
}
When I run the above code
The instance member 'stars' can't be accessed in an initializer.
Try replacing the reference to the instance member with a different expression
I get the above error.
For the time being
==> Make ratings and stars a function.
==> Make the ratings and stars variables local variables of the build () method.
When I changed it as above, the error disappeared, but I'm not sure why the above code gives an error.
What's the reason?
move variables into build method, or you can defined theirs as getter
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart' show debugPaintSizeEnabled;
void main() {
debugPaintSizeEnabled = true; // Remove to suppress visual layout
runApp(MyApp());
}
class MyApp extends StatelessWidget {
Widget get stars => Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.star, color: Colors.green[500]),
Icon(Icons.star, color: Colors.green[500]),
Icon(Icons.star, color: Colors.black),
Icon(Icons.star, color: Colors.black),
Icon(Icons.star, color: Colors.black),
],
);
Widget get ratings => Container(
padding: EdgeInsets.all(20),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
stars,
Text(
'130 Reviews',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w800,
fontFamily: 'Roboto',
letterSpacing: 0.5,
fontSize: 20,
),
),
],
),
);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter layout demo',
home: Scaffold(
appBar: AppBar(
title: Text('Flutter layout demo'),
),
// Change to buildColumn() for the other column example
body: ratings,
),
);
}
}
reason :
in dart you can't create a class level variable depends with another variable
another way is define stars variable as static variable :
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart' show debugPaintSizeEnabled;
void main() {
debugPaintSizeEnabled = true; // Remove to suppress visual layout
runApp(MyApp());
}
class MyApp extends StatelessWidget {
static Widget stars=Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.star, color: Colors.green[500]),
Icon(Icons.star, color: Colors.green[500]),
Icon(Icons.star, color: Colors.black),
Icon(Icons.star, color: Colors.black),
Icon(Icons.star, color: Colors.black),
],
);
Widget ratings = Container(
padding: EdgeInsets.all(20),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
stars,
Text(
'130 Reviews',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w800,
fontFamily: 'Roboto',
letterSpacing: 0.5,
fontSize: 20,
),
),
],
),
);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter layout demo',
home: Scaffold(
appBar: AppBar(
title: Text('Flutter layout demo'),
),
// Change to buildColumn() for the other column example
body: ratings,
),
);
}
}
You can't accessed method where it define. To use add your method below the build (i.e. above the return function)
Widget stars=Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.star, color: Colors.green[500]),
Icon(Icons.star, color: Colors.green[500]),
Icon(Icons.star, color: Colors.black),
Icon(Icons.star, color: Colors.black),
Icon(Icons.star, color: Colors.black),
],
);
Widget ratings = Container(
padding: EdgeInsets.all(20),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
stars,
Text(
'130 Reviews',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w800,
fontFamily: 'Roboto',
letterSpacing: 0.5,
fontSize: 20,
),
),
],
),
);
I created a search function with new class extends SearchDelegate. And I want to custom appBar background color, font size. How to achieve this?
My search class
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],
),
),
],
),
))
],
),
),
);
},
);
}
}
This class create a appbar like this
When I try to change backgound color use
ThemeData appBarTheme(BuildContext context) {
return ThemeData(
primaryColor: Color(0xff202c3b),
);
}
Background color changed but some style are changed too
I want to custom a little bit style like
Font size bigger
Font color to white
Don't use underline
How to achieve this? I can't find any TextStyle or something like that
EDITED
CountryPage class for use search
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));
},
);
}
The following works flawlessly:
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),
),
);
}
}
You can provide style to the title like this:
title: Text("MyApp", style:TextStyle(color:Colors.black,fontWeight:FontWeight.w300,fontSize:20)
and for the underline add the following attribute
decoration:TextDecoration.none
you have to add this in AppBar() properties.
So finally:
title: Text("MyApp",
style:TextStyle(
color:Colors.black,
fontWeight:FontWeight.w300,
fontSize:20,
decoration:TextDecoration.none
)
I understand the issue, and my solution won't fix the whole problem, but if what you want is just change some of the appBarTheme properties, you can do so by using the .copyWith method and indicating what are the properties that you want to override.
#override
ThemeData appBarTheme(BuildContext context) {
// TODO: implement appBarTheme
return super.appBarTheme(context).copyWith(//OVERRIDE PROPERTIES HERE);
}
You can override your appBarTheme like this :
#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,
),
),
);
}
You could use appBarTheme Method from SearchDelegate class for changing AppBar Theme. (https://api.flutter.dev/flutter/material/SearchDelegate-class.html)
Examples:
// 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),
),
);
}