Why am I getting dart:html not found? - flutter

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?

Related

Flutter debug banner not removed

hi i used the debugShowCheckedModeBanner:false inside the materialApp widget and but still the debug banner did not disappear . Any solution please
and thank you
hi i used the debugShowCheckedModeBanner:false inside the materialApp widget and but still the debug banner did not disappear . Any solution please
and thank you
import 'dart:convert';
import 'dart:io';
import 'package:az/SR_Details.dart';
import 'package:az/main.dart';
import 'package:badges/badges.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import 'class/sr.dart';
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner:false,
home: DataFromAPI(),
);
}
}
class DataFromAPI extends StatefulWidget {
#override
_DataFromAPIState createState() => _DataFromAPIState();
}
List<Attributes> _MyAllData = [];
List<Attributes> filteredSR=[];
var srAttributes = [];
Map<String, Color> map={
"QUEUED":Color.fromARGB(255, 255, 136, 0),
"CLOSED":Colors.grey,
"Rejeced":Colors.red,
"INPROG":Colors.green,
"PENDING":Colors.blue,
"RESOLVED":Colors.green,
"NEW":Colors.blue,
};
Map<dynamic, String> map1={
1 :"Urgent",
2:"High",
3:"Medium",
4:"Low",
};
class _DataFromAPIState extends State<DataFromAPI> {
var var1;
String title_string = "Liste des SR";
#override
void initState() {
loadData().then((value) {
setState(() {
srAttributes.addAll(value);
// filteredSR=srAttributes;
});
});
super.initState();
}
void setappbar(numsr) {
setState((){
title_string =numsr.toString();
});
}
Future<List<Sr>> loadData() async {
try {
var response = await http.get(Uri.parse(
'http://192:9080/maxrest/rest/mbo/sr/?_lid= &_lpwd= &_format=json'));
if (response.statusCode == 200) {
//print(response.body);
final jsonBody = json.decode(response.body);
Demandes data = Demandes.fromJson(jsonBody);
final srAttributes = data.srMboSet.sr;
title_string='Liste des SR : ${srAttributes.length.toString()}';
return srAttributes;
}
} catch (e) {
throw Exception(e.toString());
}
throw Exception("");
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: new Scaffold( appBar: AppBar(
title: Text(title_string),
leading: IconButton(
icon: Icon(Icons.arrow_back), onPressed: () { Navigator.push(
context, MaterialPageRoute(builder: (context) => Home())); },
),
),
body: FutureBuilder<List<Sr>?>(
future: loadData(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return SizedBox(
height: MediaQuery.of(context).size.height / 1.3,
child: Center(
child: CircularProgressIndicator(),
),
);
} else {
return new ListView.builder(
itemCount: snapshot.data?.length,
itemBuilder: ((_, index) {
return index == 0
? _searchbar()
:
new ListTile(
title: new Card(
margin: new EdgeInsets.symmetric(
vertical: 2.0, horizontal: 8.0),
elevation: 10,
child: new ListTile(
title: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(padding: new EdgeInsets.all(2.0)),
Row(children :[
Container(
decoration: BoxDecoration(
border: Border.all(
color: Color.fromARGB(255, 255, 255, 255),
),
color: map['${snapshot.data![index].attributes.status.content}'],
borderRadius: BorderRadius.all(Radius.circular(20)),
),
child:Text(' ${snapshot.data![index].attributes.status.content} '),
),
Container(child: Text(' '),),
Container(
decoration: BoxDecoration(
border: Border.all(
color: Color.fromARGB(255, 255, 255, 255),
),
color:Colors.grey,
borderRadius: BorderRadius.all(Radius.circular(20)),
),
child:Text(
" High "),
),
],
),
SizedBox(
height: 8,
),
Row(children: <Widget>[
Expanded( child: Container(child: Text('${snapshot.data![index].attributes.description?.content}',style: GoogleFonts.openSans(
textStyle: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600)),),),),
Expanded(child: Container(child:Text( ' ${snapshot.data![index].attributes.ticketid.content}',style: GoogleFonts.openSans(
textStyle: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w400)),)))
],),
new Divider(
color: Color.fromARGB(255, 110, 109, 109),
),
Text(
'Reported : ${DateFormat.yMMMMEEEEd().format(DateTime.parse('${snapshot.data![index].attributes.statusdate.content}' ))}' ,
style: GoogleFonts.openSans(
textStyle: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w400)),
),
new Text(
'Reported by : ${snapshot.data![index].attributes.reportedby?.content}',style: GoogleFonts.openSans(
textStyle: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w400)),
),
Row(children: [new Image(image: AssetImage('assets/courroi.png'), width: 20),
Text(
'${snapshot.data![index].attributes.assetnum?.content}'),], ),
Row(children: [new Image(image: AssetImage('assets/location1.png'), width: 20),
Text(
'${snapshot.data![index].attributes.assetsiteid?.content}'),], ) ,
],
),
trailing: Icon(Icons.arrow_forward_ios_rounded),
),
),
onTap: () {
/* Navigator.push(
context,MaterialPageRoute(builder: (context) =>SRDetail()),
);*/
}
);
}),
);
}
},
),
),
);
}
You DataFromAPI has another MaterialApp without that parameter. I'd suggest to remove it there because now you have a MaterialApp inside a MaterialApp
You have two material app in your code,
remove this material app
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner:false,
home: DataFromAPI(),
);
}
}
and return
DataFromAPI(),
Add debugShowCheckedModeBanner inside DataFromAPI MaterialApp widget.
MaterialApp(
debugShowCheckedModeBanner:false,
home: new Scaffold( appBar: AppBar(
title: Text(title_string),
leading: IconButton(
icon: Icon(Icons.arrow_back), onPressed: () { Navigator.push(
context, MaterialPageRoute(builder: (context) => Home())); },
),
),
.........

Navigator.push it doesn't work how can i fix it?

I created 3 files, in the second file I put it inside the Elevatedbutton, but when I press the button I don't go to the other pagethe first it has this code :
import 'package:flutter/material.dart';
import 'Firstpage.dart';
void main (){
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: FirstPage(),
);
}
}
in the second file i have :
import 'package:flutter/material.dart';
import 'planetspage.dart';
class FirstPage extends StatefulWidget {
const FirstPage({Key? key}) : super(key: key);
#override
State<FirstPage> createState() => _FirstPageState();
}
class _FirstPageState extends State<FirstPage> {
var lang = "en";
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Stack(
children: [
Image.asset(
'images/firstwal.jpg',
width: double.infinity,
fit: BoxFit.cover,
),
Container(
padding: const EdgeInsets.all(15),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
const Text(
'Explore space',
style: TextStyle(
fontSize: 35,
color: Colors.white,
fontWeight: FontWeight.w500),
),
const SizedBox(
height: 10,
),
const Text(
'a system of millions or billions of stars, together with gas and dust, held together by gravitational attraction.',
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 20,
color: Colors.white),
),
const SizedBox(
height: 30,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
ClipRRect(
borderRadius: const BorderRadius.all(Radius.circular(30)),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 40),
color: Colors.white,
child: DropdownButton(
items: [
"en",
"ar",
]
.map((e) => DropdownMenuItem(
child: Text(e),
value: e,
))
.toList(),
onChanged: (val) {
setState(() {
lang = val.toString();
});
},
value: lang,
style:
const TextStyle(color: Colors.black87, fontSize: 20),
iconEnabledColor: Colors.black87,
)),
),
ClipRRect(
borderRadius: const BorderRadius.all(Radius.circular(30)),
child: ElevatedButton(
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context)=> const enPlanetspage()));
},
style: ElevatedButton.styleFrom(
primary: Colors.deepPurple),
child: Container(
padding: const EdgeInsets.symmetric(
vertical: 10, horizontal: 20),
child: Row(
children: const [
Text(
'Next',
style: TextStyle(
color: Colors.white,
fontSize: 20,
),
),
Icon(Icons.navigate_next_outlined),
],
),
)),
),
],
),
],
),
),
],
),
),
);
}
}
when i press the button Navigator.push doesn't work how can i fix it?
I created 3 files, in the second file I put it inside the Elevatedbutton, but when I press the button I don't go to the other pagethe first it has this code :
Try using:
onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (context)=> const enPlanetspage()));
Check if your image files are mentioned in the pubsec.

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

How to custom appbar style inside SearchDelegate

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

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