How to custom appbar style inside SearchDelegate - flutter

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),
),
);
}

Related

Why am I getting dart:html not found?

I am trying to make a quiz app and the app is running perfectly but there is this passive error
lib/main.dart:4:8: Error: Not found: 'dart:html'
import 'dart:html';
Here is my code
import 'package:flutter/material.dart';
import 'dart:html';
void main() {
runApp(QuizApp());
}
List questionBank = [...];
class QuizApp extends StatefulWidget {
#override
State<QuizApp> createState() => _MyAppState();
}
class _MyAppState extends State<QuizApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Home(),
);
}
}
class Home extends StatefulWidget {
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
int _currentQuestion = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
"Quiz App",
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.bold,
color: Colors.black87,
),
),
centerTitle: true,
backgroundColor: Colors.lightBlueAccent.withOpacity(0.8),
),
backgroundColor: Colors.lightBlueAccent.withOpacity(0.8),
body: Builder(
builder: (BuildContext context) {
return Container(
child: Column(
children: [
Center(
child: Image.asset(
"images/quiz_icon_3.png",
height: 265,
)),
Container(
height: 120,
width: 350,
decoration: BoxDecoration(
border: Border.all(color: Colors.black87, width: 1.5),
borderRadius: BorderRadius.circular(22),
),
child: Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
questionBank[_currentQuestion].questionText,
style: TextStyle(
fontSize: 18.5,
color: Colors.black87,
),
),
)),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
onPressed: () => _checkAnswer(true, context),
child: Text(
"True",
style: TextStyle(
fontSize: 20.5,
fontWeight: FontWeight.bold,
color: Colors.black87,
),
),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blueGrey.shade700,
),
),
ElevatedButton(
onPressed: () => _checkAnswer(false, context),
child: Text(
"False",
style: TextStyle(
fontSize: 20.5,
fontWeight: FontWeight.bold,
color: Colors.black87,
),
),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blueGrey.shade700),
),
ElevatedButton(
onPressed: () => setState(() {
_nextQuestion();
}),
child: Icon(
Icons.arrow_forward_ios,
color: Colors.black87,
),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blueGrey.shade700),
)
],
)
],
),
);
}
),
);
}
_nextQuestion() {
if (_currentQuestion == questionBank.length - 1) {
_currentQuestion = 0;
} else {
_currentQuestion++;
}
}
_checkAnswer(bool useChoice, BuildContext context) {
if (questionBank[_currentQuestion].isTrue = useChoice) {
var correctBar = SnackBar(content: Text("CORRECT !"));
ScaffoldMessenger.of(context).showSnackBar(correctBar);
} else {
var falseBar = SnackBar(content: Text("False !"));
ScaffoldMessenger.of(context).showSnackBar(falseBar);
}
}
}
class Questions {
String questionText;
bool isTrue;
Questions(this.questionText, this.isTrue);
}
I have tried importing both dart:html and io, each seperate, but nothing
I suspect the error is related to the snackBar function, or the build widget I added.
Any help will be appreciated, thank you.
just curious.
Are you using "dart:html" for something?
I faced similar issues, and just removing
'import 'dart:html';
works for me, unless you really need it.
using import 'dart:html' in flutter - Do I need additional dependencies?

How to change the color PageView Slider in Flutter?

I don't know what actually it called so I randomly asked a question and ignore all the grammar mistakes just give me a solution of my problem. I want to change that blue color to orange color when I slide to end page and i am a beginner in flutter so i need help...
This is my OnboardingScreen.dart file
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:secret_partner/data/data.dart';
class OnboardingScreen extends StatefulWidget {
#override
_OnboardingScreenState createState() => _OnboardingScreenState();
}
class _OnboardingScreenState extends State<OnboardingScreen> {
List<SliderModel> mySLides = new List<SliderModel>();
int slideIndex = 0;
PageController controller;
Widget _buildPageIndicator(bool isCurrentPage){
return Container(
margin: EdgeInsets.symmetric(horizontal: 2.0),
height: isCurrentPage ? 10.0 : 6.0,
width: isCurrentPage ? 10.0 : 6.0,
decoration: BoxDecoration(
color: isCurrentPage ? Colors.grey : Colors.grey[300],
borderRadius: BorderRadius.circular(12),
),
);
}
#override
void initState() {
// TODO: implement initState
super.initState();
mySLides = getSlides();
controller = new PageController();
}
#override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [const Color(0xFF9E9E9E), const Color(0xFFE0E0E0)])),
child: Scaffold(
backgroundColor: Colors.white,
body: Container(
height: MediaQuery.of(context).size.height - 50,
child: PageView(
controller: controller,
onPageChanged: (index) {
setState(() {
slideIndex = index;
});
},
children: <Widget>[
SlideTile(
imagePath: mySLides[0].getImageAssetPath(),
title: mySLides[0].getTitle(),
desc: mySLides[0].getDesc(),
),
SlideTile(
imagePath: mySLides[1].getImageAssetPath(),
title: mySLides[1].getTitle(),
desc: mySLides[1].getDesc(),
),
SlideTile(
imagePath: mySLides[2].getImageAssetPath(),
title: mySLides[2].getTitle(),
desc: mySLides[2].getDesc(),
)
],
),
),
bottomSheet: slideIndex != 2 ? Container(
margin: EdgeInsets.symmetric(vertical: 1),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
FlatButton(
onPressed: (){
controller.animateToPage(2, duration: Duration(milliseconds: 400), curve: Curves.linear);
},
splashColor: Colors.orange[200],
child: Text(
"SKIP",
style: TextStyle(color: Color(0xFFF57C00), fontWeight: FontWeight.w600),
),
),
Container(
child: Row(
children: [
for (int i = 0; i < 3 ; i++) i == slideIndex ? _buildPageIndicator(true): _buildPageIndicator(false),
],),
),
FlatButton(
onPressed: (){
print("this is slideIndex: $slideIndex");
controller.animateToPage(slideIndex + 1, duration: Duration(milliseconds: 500), curve: Curves.linear);
},
splashColor: Colors.grey[200],
child: Text(
"NEXT",
style: TextStyle(color: Color(0xFFF57C00), fontWeight: FontWeight.w600),
),
),
],
),
): InkWell(
onTap: (){
print("Get Started Now");
},
child: Container(
height: Platform.isIOS ? 60 : 50,
color: Colors.deepOrange,
alignment: Alignment.center,
child: Text(
"GET STARTED NOW",
style: TextStyle(color: Colors.white, fontWeight: FontWeight.w600),
),
),
),
),
);
}
}
class SlideTile extends StatelessWidget {
final String imagePath, title, desc;
SlideTile({this.imagePath, this.title, this.desc});
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.symmetric(horizontal: 20),
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image.asset(imagePath),
SizedBox(
height: 40,
),
Text(title, textAlign: TextAlign.center,style: TextStyle(
fontWeight: FontWeight.w500,
fontSize: 20
),),
SizedBox(
height: 20,
),
Text(desc, textAlign: TextAlign.center,style: TextStyle(
fontWeight: FontWeight.w500,
fontSize: 14))
],
),
);
}
}
My data.dart file
class SliderModel{
String imageAssetPath;
String title;
String desc;
SliderModel({this.imageAssetPath,this.title,this.desc});
void setImageAssetPath(String getImageAssetPath){
imageAssetPath = getImageAssetPath;
}
void setTitle(String getTitle){
title = getTitle;
}
void setDesc(String getDesc){
desc = getDesc;
}
String getImageAssetPath(){
return imageAssetPath;
}
String getTitle(){
return title;
}
String getDesc(){
return desc;
}
}
List<SliderModel> getSlides(){
List<SliderModel> slides = new List<SliderModel>();
SliderModel sliderModel = new SliderModel();
//1
sliderModel.setDesc("Discover Restaurants offering the best fast food food near you on Foodwa");
sliderModel.setTitle("Search");
sliderModel.setImageAssetPath("assets/images/illustration.png");
slides.add(sliderModel);
sliderModel = new SliderModel();
//2
sliderModel.setDesc("Our veggie plan is filled with delicious seasonal vegetables, whole grains, beautiful cheeses and vegetarian proteins");
sliderModel.setTitle("Order");
sliderModel.setImageAssetPath("assets/images/illustration2.png");
slides.add(sliderModel);
sliderModel = new SliderModel();
//3
sliderModel.setDesc("Food delivery or pickup from local restaurants, Explore restaurants that deliver near you.");
sliderModel.setTitle("Eat");
sliderModel.setImageAssetPath("assets/images/illustration3.png");
slides.add(sliderModel);
sliderModel = new SliderModel();
return slides;
}
You can change accentColor in your MaterialApp of main.dart as,
return MaterialApp(
theme: ThemeData(
accentColor: Colors.red,
),
home: MyApp(),
);
Or you can wrap your PageView with Theme as below,
Theme(
data: ThemeData(
accentColor: Colors.red,
),
child: PageView(
...
),
),
Try With this
void main() {
runApp(MaterialApp(
theme: ThemeData(
accentColor: Colors.orange
),
home: MyApp(),
));
}
Since the question was asked years back, Now the accentColor is deprecated.
So, you can use the below code:
Theme(
data: ThemeData(
colorScheme: ColorScheme.fromSwatch().copyWith(secondary: Colors.deepPurple),
),
);

Flutter passing data and calling out method from a stateful widget to another statefulwidget

Good day! I have here some block of codes of my MainMenu page and Drawer.
I need to pass data from MainMenu which is a statefulwidget to Drawer which is also a statefulwidget so that I can use the datas and method from MainMenu.
Can someone help me or reproduce my code below.
class MainMenu extends StatefulWidget {
final VoidCallback signOut;
MainMenu(this.signOut);
#override
_MainMenuState createState() => _MainMenuState();
}
class _MainMenuState extends State<MainMenu> {
int index = 0;
List<Widget> list = [
HomeScreen(),
Stations(),
AccountPage(),
];
signOut() {
setState(() {
widget.signOut();
});
}
int currentIndex = 0;
String selectedIndex = 'TAB: 0';
String email = "", id = "", fname= "";
TabController tabController;
getPref() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
setState(() {
id = preferences.getString('id');
email = preferences.getString('email');
fname = preferences.getString('fname');
});
print("id:" + id);
print("user:" + email);
print("address:" + fname);
}
#override
void initState() {
// TODO: implement initState
super.initState();
getPref();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
actions: <Widget>[
IconButton(
onPressed: () {
signOut();
},
icon: Icon(Icons.lock_open),
)
],
backgroundColor: Color(0xFF262AAA),
iconTheme: IconThemeData(color: Colors.lightBlue),
centerTitle: true,
title: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('DVO',
style: TextStyle(color: Colors.lightBlue,fontWeight: FontWeight.w700),
),
SizedBox(width: 1.3),
Text(
'REPORT',
style: TextStyle(color: Colors.white,fontWeight: FontWeight.w700),
),
],
),
elevation: 0,
),
body: list[index],
drawer: MyDrawer(onTap: (lol, i) {
setState(() {
index = i;
Navigator.pop(lol);
});
}),
),
);
}
}
class MyDrawer extends StatefulWidget {
#override
_MyDrawerState createState() => _MyDrawerState();
}
class _MyDrawerState extends State<MyDrawer> {
Function onTap;
_MyDrawerState(
{this.onTap
});
#override
Widget build(BuildContext context) {
return SizedBox(
width: MediaQuery
.of(context)
.size
.width * 0.7,
child: Drawer(
child: Container(
color: Colors.white,
child: ListView(
padding: EdgeInsets.all(0),
children: <Widget>[
UserAccountsDrawerHeader(
decoration: BoxDecoration(
color: Colors.white,
image: DecorationImage(
image: AssetImage("assets/badge.jpg"),
fit: BoxFit.cover,
colorFilter: new ColorFilter.mode(Colors.black.withOpacity(0.8), BlendMode.dstATop)),
),
accountEmail: Text("dummy#gmail.com"),
accountName: Text("Dummy",
style: TextStyle(color: Colors.white,fontWeight: FontWeight.w700, fontSize: 25),
),
currentAccountPicture: CircleAvatar(
backgroundColor: Colors.grey[400],
child: Icon(
Icons.perm_identity,
color: Colors.white,
),
),
),
ListTile(
selected: true,
leading: Icon(Icons.announcement, color: Colors.cyan,size: 26.0),
title: Text("News And Announcements",
style: TextStyle(color: Colors.black,fontWeight: FontWeight.w500, fontSize: 18),
),
onTap: () => onTap(context, 0),
),
ListTile(
leading: Icon(Icons.place,color: Colors.cyan, size: 30.0),
title: Text("Stations",
style: TextStyle(color: Colors.black,fontWeight: FontWeight.w500, fontSize: 18),
),
onTap: () => onTap(context, 1),
),
ListTile(
leading: Icon(Icons.settings,color: Colors.cyan, size: 30.0),
title: Text("Account Settings",
style: TextStyle(color: Colors.black,fontWeight: FontWeight.w500, fontSize: 18),
),
onTap: () => onTap(context, 2),
),
Divider(
height: 595,
thickness: 0.5,
color: Colors.white.withOpacity(0.3),
indent: 32,
endIndent: 32,
),
ListTile(
leading: Icon(Icons.exit_to_app,color: Colors.cyan, size: 30.0),
onTap: () {
//widget.signOut();
},
title: Text("Logout",
style: TextStyle(color: Colors.black,fontWeight: FontWeight.w500, fontSize: 18),
),
),
],
),
),
),
);
}
}
I'm getting this error on build widget in MainMenu.
The named parameter 'onTap' isn't defined.
Try correcting the name to an existing named parameter's name, or defining a named parameter with the name 'onTap'.
This part:
Function onTap;
_MyDrawerState({this.onTap});
This parameter and its presence in the constructor should be in the MyDrawer public class rather than a private State class.
The specified error comes because MyDrawer class doesn't have this.
You can access onTap function in _MyDrawerState through the widget variable which is an instance of MyDrawer class

Get Time Picker's Value within a Widget

I am trying to get the DateTime that is chosen from the user and save it within an object.
This is implemented within the following construction:
return Scaffold(
appBar: AppBar(
title: Text('Add/Edit Shift'),
),
body: Container(
color: Colors.white,
margin: EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: SingleChildScrollView(
child: Column(
// crossAxisAlignment: CrossAxisAlignment.center,
// mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
height: 40.0,
decoration:
BoxDecoration(borderRadius: BorderRadius.circular(5.0)),
alignment: Alignment.center,
width: MediaQuery.of(context).size.width,
child: Text(
'Scheduling Date: ${_dateformat.format(widget.shiftDate)}',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 19.0,
color: Colors.teal,
),
),
),
// fixme: how to get the clicked value from the user?
// the value has to get saved within an object that will be returned
MyTimePicker(_startOfShift),
MyTimePicker(_endOfShift),
RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5.0),
),
child: Text(
"Submit",
style: TextStyle(
color: Colors.teal,
fontSize: 18.0,
fontWeight: FontWeight.bold),
),
onPressed: () {
// todo: return the shift to the calendar
// print(MyTimePicker(_startOfShift).chosenTime);
Navigator.pop(
context,
);
},
)
],
),
),
),
),
);
And this is how it looks like:
The MyTimePickerClass is created as a separate Dart file. Within the MyTimePicker class, I construct a RaisedButton labeled as Start and End where the user is capable to choose the wanting time.
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
class MyTimePicker extends StatefulWidget {
String typeOfShift;
MyTimePicker(this.typeOfShift);
#override
_MyTimePickerState createState() => _MyTimePickerState();
}
class _MyTimePickerState extends State<MyTimePicker> {
#override
Widget build(BuildContext context) {
return RaisedButton(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)),
elevation: 4.0,
onPressed: () {
DateTime test = _MyDatePicker(context);
widget.typeOfShift = test.toString();
setState(() {});
},
child: Container(
alignment: Alignment.center,
height: 50.0,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Row(
children: <Widget>[
Container(
child: Row(
children: <Widget>[
Icon(
Icons.access_time,
size: 18.0,
color: Colors.teal,
),
Text(
" ${widget.typeOfShift}",
style: TextStyle(
color: Colors.teal,
fontWeight: FontWeight.bold,
fontSize: 18.0),
),
],
),
)
],
),
Text(
" Change",
style: TextStyle(
color: Colors.teal,
fontWeight: FontWeight.bold,
fontSize: 18.0),
),
],
),
),
color: Colors.white,
);
}
DateTime _MyDatePicker(BuildContext context) {
DateTime _myDateTime;
DatePicker.showTimePicker(context,
showSecondsColumn: false,
theme: DatePickerTheme(
containerHeight: 210.0,
),
showTitleActions: true, onConfirm: (time) {
// _chosenTime = time;
_myDateTime = time;
print('confirm $time');
// widget.typeOfShift = '${time.hour} : ${time.minute}';
setState(() {});
}, currentTime: DateTime.now(), locale: LocaleType.de);
return _myDateTime;
}
}
Then the time is displayed in the UI. How could I access this time??
You can copy paste run full code below
You can define two MyTimePicker and use it
When onPressed , you can use startPicker.typeOfShift to get String
MyTimePicker startPicker = MyTimePicker("Start");
MyTimePicker endPicker = MyTimePicker("End");
...
startPicker,
endPicker,
RaisedButton(
...
onPressed: () {
print(startPicker.typeOfShift);
print(endPicker.typeOfShift);
output
I/flutter (31204): 1 : 23
I/flutter (31204): 1 : 25
working demo
full code
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
class MyTimePicker extends StatefulWidget {
String typeOfShift;
MyTimePicker(this.typeOfShift);
#override
_MyTimePickerState createState() => _MyTimePickerState();
}
class _MyTimePickerState extends State<MyTimePicker> {
#override
Widget build(BuildContext context) {
return RaisedButton(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)),
elevation: 4.0,
onPressed: () {
DateTime test = _MyDatePicker(context);
widget.typeOfShift = test.toString();
setState(() {});
},
child: Container(
alignment: Alignment.center,
height: 50.0,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Row(
children: <Widget>[
Container(
child: Row(
children: <Widget>[
Icon(
Icons.access_time,
size: 18.0,
color: Colors.teal,
),
Text(
" ${widget.typeOfShift}",
style: TextStyle(
color: Colors.teal,
fontWeight: FontWeight.bold,
fontSize: 18.0),
),
],
),
)
],
),
Text(
" Change",
style: TextStyle(
color: Colors.teal,
fontWeight: FontWeight.bold,
fontSize: 18.0),
),
],
),
),
color: Colors.white,
);
}
DateTime _MyDatePicker(BuildContext context) {
DateTime _myDateTime;
DatePicker.showTimePicker(context,
showSecondsColumn: false,
theme: DatePickerTheme(
containerHeight: 210.0,
),
showTitleActions: true, onConfirm: (time) {
// _chosenTime = time;
_myDateTime = time;
print('confirm $time');
widget.typeOfShift = '${time.hour} : ${time.minute}';
setState(() {});
}, currentTime: DateTime.now(), locale: LocaleType.de);
return _myDateTime;
}
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
MyTimePicker startPicker = MyTimePicker("Start");
MyTimePicker endPicker = MyTimePicker("End");
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Add/Edit Shift'),
),
body: Container(
color: Colors.white,
margin: EdgeInsets.all(16.0),
child: Form(
//key: _formKey,
child: SingleChildScrollView(
child: Column(
// crossAxisAlignment: CrossAxisAlignment.center,
// mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
height: 40.0,
decoration:
BoxDecoration(borderRadius: BorderRadius.circular(5.0)),
alignment: Alignment.center,
width: MediaQuery.of(context).size.width,
child: Text(
'Scheduling Date: ',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 19.0,
color: Colors.teal,
),
),
),
// fixme: how to get the clicked value from the user?
// the value has to get saved within an object that will be returned
startPicker,
endPicker,
RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5.0),
),
child: Text(
"Submit",
style: TextStyle(
color: Colors.teal,
fontSize: 18.0,
fontWeight: FontWeight.bold),
),
onPressed: () {
print(startPicker.typeOfShift);
print(endPicker.typeOfShift);
// todo: return the shift to the calendar
// print(MyTimePicker(_startOfShift).chosenTime);
Navigator.pop(
context,
);
},
)
],
),
),
),
),
);
}
}

Flutter state widget is not updated

I want to put a book as bookmarked, and if I click in the favorite button, the book is added, but when I go to another window and come back, the icon button change color.
CupertinoButton(
child: Icon(
widget.book.starred
?
CupertinoIcons.heart_solid
: CupertinoIcons.heart,
color: Colors.red,
),
onPressed: () {
setState(() {
widget.book.starred = !widget.book.starred;
addToFavorites(this.book);
});
})//Cupertino Button
How can I handle the build method to read the value of widget.book.starred and then print the right icon ?
EDIT
to show more code
class ReadBook extends StatefulWidget {
Book book;
ReadBook({Key key, this.book}) : super(key: key);
#override
State<StatefulWidget> createState() {
return new ReadBookState(this.book);
}
}
class ReadBookState extends State<ReadBook> {
// Declare a field that holds the Todo
Book book;
bool res;
final controller = new PageController(initialPage: 0, keepPage: true);
static const IconData baseball = const IconData(0xf397,
fontFamily: CupertinoIcons.iconFont,
fontPackage: CupertinoIcons.iconFontPackage);
ReadBookState(this.book);
initState() {
super.initState();
}
void addToFavorites(Book book) async {
Database.checkBookExist(book).then((value) {
if (!value) {
print("${widget.book.englishName} added successfully");
Database.addBookToFirestore(widget.book);
} else {
print("${widget.book.englishName} already added");
}
});
#override
Widget build(BuildContext context) {
Widget toRet;
bool rest = retrieveFromFavorites(book);
if (Platform.isAndroid) {
// Android-specific code
toRet = MaterialApp(
home: Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () => Navigator.pop(context, false),
),
actions: <Widget>[],
backgroundColor: Color.fromRGBO(245, 205, 121, 1.0),
title: Text(book.name,
textDirection: TextDirection.rtl,
style:
TextStyle(fontSize: 35.0, fontFamily: 'SCHEHERAZADE')),
),
body: new ListView(
controller: controller,
scrollDirection: Axis.vertical,
children: <Widget>[
new Center(
child: new Text(("Title"),
textDirection: TextDirection.rtl,
style: TextStyle(
fontSize: 35.0, fontFamily: 'SCHEHERAZADE'))),
new Center(
child: new Text((t1 + t2),
textDirection: TextDirection.rtl,
style: TextStyle(
fontSize: 25.0, fontFamily: 'SCHEHERAZADE')))
],
)));
} else if (Platform.isIOS) {
// iOS-specific code
toRet = CupertinoApp(
home: CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
backgroundColor: Color.fromRGBO(245, 205, 121, 1.0),
leading: CupertinoButton(
padding: EdgeInsets.only(right: 25.0, bottom: 8.0),
child: Icon(
CupertinoIcons.back,
color: Colors.black,
),
onPressed: () => Navigator.pop(context, false),
),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
CupertinoButton(
child: Icon(
widget.book.starred
?
CupertinoIcons.heart_solid
: CupertinoIcons.heart,
color: Colors.red,
),
onPressed: () {
// PopupMenuButton
setState(() {
widget.book.starred = !widget.book.starred;
addToFavorites(this.book);
});
}),
CupertinoButton(
child: Icon(
baseball,
color: Colors.black,
),
onPressed: () =>
// PopupMenuButton
popUpOptionsButton()),
],
),
middle: Text(book.name),
),
child: new ListView(
controller: controller,
scrollDirection: Axis.vertical,
children: <Widget>[
new Center(
child: new Text(("Title"),
textDirection: TextDirection.rtl,
style: TextStyle(
fontSize: 35.0, fontFamily: 'SCHEHERAZADE'))),
new Center(
child: new Text((t1 + t2),
textDirection: TextDirection.rtl,
style: TextStyle(
fontSize: 25.0, fontFamily: 'SCHEHERAZADE')))
],
),
),
);
}
return toRet;
}
}