How can I make my bottom sheet look like this? - flutter

I would like make my bottom sheet like this- no background and the height and width determined by the content.
showModalBottomSheet(
context: context,
elevation: 0,
backgroundColor: Colors.transparent,
builder: (context) => Container(
height: 60,
decoration: BoxDecoration(
color: Colors.transparent,
borderRadius: BorderRadius.only(
topLeft: const Radius.circular(50.0),
topRight: const Radius.circular(50.0),
),
),
child: Container(
color: AppColors.grey8,
padding: EdgeInsets.all(12),
child: Text("Call Doctor",
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w600,
fontFamily: 'Euclid',
color: AppColors.textColor,
),)
),
),
);

Check this code,let me know this work for you
for more details check this link cupertino Widgets also refer cupertino-ios-style-actionsheet
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("CupertinoActionSheet"),
),
body: Center(
child: ElevatedButton(
onPressed: () {
final action = CupertinoActionSheet(
title: Text(
"Flutter dev",
style: TextStyle(fontSize: 30),
),
message: Text(
"Select any action ",
style: TextStyle(fontSize: 15.0),
),
actions: <Widget>[
CupertinoActionSheetAction(
child: Text("Action 1"),
isDefaultAction: true,
onPressed: () {
print("Action 1 is been clicked");
},
),
CupertinoActionSheetAction(
child: Text("Action 2"),
isDestructiveAction: true,
onPressed: () {
print("Action 2 is been clicked");
},
)
],
cancelButton: CupertinoActionSheetAction(
child: Text("Cancel"),
onPressed: () {
Navigator.pop(context);
},
),
);
showCupertinoModalPopup(
context: context, builder: (context) => action);
},
child: Text("Click me "),
),
),
);
}
}

Related

Having an issue using TextFeild in flutter, Text box not showing up

I'm creating a flutter app that requires a user to complete certain tasks in order to stop an alarm clock. It's a more immersive alarm clock app that could help stimulate the brain in order to aid in the process of waking up.
The tasks are simple questions the user has to answer. I'm utilizing TextFeild() to allow the user to input their answer. However, when I go to debug my code is redirected to a file called box.dart this is where the error is stated.
Here is the box.dart file error:
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Cannot hit test a render box with no size.'),
describeForError('The hitTest() method was called on this RenderBox'),
ErrorDescription(
'Although this node is not marked as needing layout, '
'its size is not set.',
),
ErrorHint(
'A RenderBox object must have an '
'explicit size before it can be hit-tested. Make sure '
'that the RenderBox in question sets its size during layout.',
),
]);
}
Here is my full code:
import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
//import 'package:audioplayers/audio_cache.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Time Attack',
theme: ThemeData(
primarySwatch: Colors.red,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
backgroundColor: Colors.red,
title: const Text('Time Attack'),
centerTitle: true,
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
// ignore: avoid_print
print("alarm is playing");
final player = AudioCache();
//bool isPLaying = false;
await player.load('musicForapp.mp3');
AudioPlayer p = AudioPlayer();
p.audioCache = player;
await p.play(AssetSource('musicForapp.mp3'));
},
backgroundColor: Colors.red,
child: const Icon(Icons.punch_clock),
),
body: Padding(
padding: const EdgeInsets.all(170),
child: Column(
children: [
const Text(
"Click the Icon in the bottem right to simulate alarm",
style: TextStyle(
color: Colors.white,
fontSize: 30.0,
),
),
ElevatedButton(
style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => const TasksPage(),
),
);
}, //on pressed
child: const Text(
"Tasks page",
style: TextStyle(color: Colors.white),
),
)
],
),
),
),
);
} //widget build
}
class TasksPage extends StatefulWidget {
const TasksPage({super.key});
#override
State<TasksPage> createState() => _TasksPageState();
}
class _TasksPageState extends State<TasksPage> {
final _textcontroller = TextEditingController();
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
backgroundColor: Colors.red,
title: const Text('Tasks'),
centerTitle: true,
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => const SecondTask(),
),
);
},
backgroundColor: Colors.red,
child: const Text("Next"),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
const Text(
"How many states are there in the United States of America?",
style: TextStyle(
backgroundColor: Colors.white,
color: Colors.black,
fontSize: 30.0,
),
),
Expanded(
child: TextField(
controller: _textcontroller,
decoration: InputDecoration(
hintText: "Type your answer here!",
border: const OutlineInputBorder(),
suffixIcon: IconButton(
onPressed: () {
_textcontroller.clear();
},
icon: const Icon(Icons.clear),
),
),
),
),
],
),
),
),
),
);
} //widget build
}
class SecondTask extends StatefulWidget {
const SecondTask({super.key});
#override
State<SecondTask> createState() => _SecondTask();
}
class _SecondTask extends State<SecondTask> {
final _textcontroller2 = TextEditingController();
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
backgroundColor: Colors.red,
title: const Text('Tasks'),
centerTitle: true,
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => const Thirdtask(),
),
);
},
backgroundColor: Colors.red,
child: const Text("Next"),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
const Text(
"how many oceans are there?",
style: TextStyle(
backgroundColor: Colors.white,
color: Colors.black,
fontSize: 30.0,
),
),
Expanded(
child: TextField(
controller: _textcontroller2,
decoration: InputDecoration(
hintText: "Type your answer here!",
border: const OutlineInputBorder(),
suffixIcon: IconButton(
onPressed: () {
_textcontroller2.clear();
},
icon: const Icon(Icons.clear),
),
),
),
),
],
),
),
),
),
);
} //widget build
}
class Thirdtask extends StatefulWidget {
const Thirdtask({super.key});
#override
State<Thirdtask> createState() => _Thirdtask();
}
class _Thirdtask extends State<Thirdtask> {
final _textcontroller3 = TextEditingController();
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
backgroundColor: Colors.red,
title: const Text('Tasks'),
centerTitle: true,
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => const Finaltask(),
),
);
},
backgroundColor: Colors.red,
child: const Text("Next"),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
const Text(
"What is 8 x 7?",
style: TextStyle(
backgroundColor: Colors.white,
color: Colors.black,
fontSize: 30.0,
),
),
Expanded(
child: TextField(
controller: _textcontroller3,
decoration: InputDecoration(
hintText: "Type your answer here!",
border: const OutlineInputBorder(),
suffixIcon: IconButton(
onPressed: () {
_textcontroller3.clear();
},
icon: const Icon(Icons.clear),
),
),
),
),
],
),
),
),
),
);
} //widget build
}
class Finaltask extends StatefulWidget {
const Finaltask({super.key});
#override
State<Finaltask> createState() => _Finaltask();
}
class _Finaltask extends State<Finaltask> {
final _textcontroller4 = TextEditingController();
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
backgroundColor: Colors.red,
title: const Text('Tasks'),
centerTitle: true,
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => const Congrats(),
),
);
},
backgroundColor: Colors.red,
child: const Text("Submit"),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
const Text(
"Riddle: What goes up but never comes back down?",
style: TextStyle(
backgroundColor: Colors.white,
color: Colors.black,
fontSize: 30.0,
),
),
Expanded(
child: TextField(
controller: _textcontroller4,
decoration: InputDecoration(
hintText: "Type your answer here!",
border: const OutlineInputBorder(),
suffixIcon: IconButton(
onPressed: () {
_textcontroller4.clear();
},
icon: const Icon(Icons.clear),
),
),
),
),
],
),
),
),
),
);
} //widget build
}
class Congrats extends StatefulWidget {
const Congrats({super.key});
#override
State<Congrats> createState() => _Congrats();
}
class _Congrats extends State<Congrats> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
backgroundColor: Colors.red,
title: const Text('Good Job!'),
centerTitle: true,
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => const MyHomePage(),
),
);
//player.clear('explosion.mp3'); (to stop alarm)
// ignore: avoid_print
print("Alarm has stoped");
},
backgroundColor: Colors.red,
child: const Text("Home"),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: const [
Expanded(
child: Text(
"Congratulations you completed your tasks, Click the home button to return home and stop the timer!",
style: TextStyle(
backgroundColor: Colors.white,
color: Colors.black,
fontSize: 30.0,
),
),
),
],
),
),
),
),
);
} //widget build
}
Firstly, please delete all MaterialApp (except the first on the top). Because in Flutter app there must be only one MaterialApp throughout the code.
Secondly, juste change your padding 170 to 17 for exemple. 170 is extremely big.
Use single MaterialApp on top widget as #Antonin Liehn said. Now for the TextFormField border. You need to use enabledBorder, also try others border property , Find more about OutlineInputBorder.
decoration: InputDecoration(
hintText: "Type your answer here!",
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.white,
width: 22,
),
),
errorBorder: ,
focusedBorder: ,
disabledBorder: ,
focusedErrorBorder: ,
border: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.white,
width: 22,
),
),
Also wrap text with Flexible/Expanded widget. You cal follow this widget
class TasksPage extends StatefulWidget {
const TasksPage({super.key});
#override
State<TasksPage> createState() => _TasksPageState();
}
class _TasksPageState extends State<TasksPage> {
final _textcontroller = TextEditingController();
final border = const OutlineInputBorder(
borderSide: BorderSide(
color: Colors.white,
width: 22,
));
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
backgroundColor: Colors.red,
title: const Text('Taskssssssss'),
centerTitle: true,
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => const SecondTask(),
),
);
},
backgroundColor: Colors.red,
child: const Text("Next"),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Flexible(
child: const Text(
"How many states are there in the United States of America?",
style: TextStyle(
backgroundColor: Colors.white,
color: Colors.black,
fontSize: 30.0,
),
),
),
Expanded(
child: TextFormField(
controller: _textcontroller,
decoration: InputDecoration(
hintText: "Type your answer here!",
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.white,
),
),
errorBorder: border,
focusedBorder: border,
disabledBorder: border,
focusedErrorBorder: border,
border: border,
suffixIcon: IconButton(
onPressed: () {
_textcontroller.clear();
},
icon: const Icon(Icons.clear),
),
),
),
),
],
),
),
),
);
} //widget build
}

Getting error while using onTap function to navigate from a Card to a new page

I'm really new to flutter and coding in general. I want to create an app to aid in Pharmacology classes. The central question is, I want to click on a Card, and this card will lead me to a new page. However, when I programmed to function, It is returned an error. I can't find where is the error. Can anyone help me?
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Farmacologia Odontológica',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: const Splash(),
);
}
}
class Splash extends StatefulWidget {
const Splash({Key? key}) : super(key: key);
#override
State<Splash> createState() => _SplashState();
}
class _SplashState extends State<Splash> {
#override
void initState() {
// TODO: implement initState
super.initState();
Future.delayed(const Duration(seconds: 2), () {
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => const HomePage()));
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.teal,
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset('icons/Pilulas.png', height: 230,width: 230,),
const SizedBox(height: 30,),
if (Platform.isIOS)
const CupertinoActivityIndicator(
radius: 15,
)
else
const CircularProgressIndicator(
color: Colors.white,
)
],
),
),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.teal,
centerTitle: true,
title: Text('Farmacologia Odontológica',style: TextStyle(
fontFamily: 'fonts/Quicksand-Light.ttf',
fontSize: 22,
),),
),
body: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(padding: const EdgeInsets.only(top:10,bottom: 10),),
Text('Classes de Medicamentos', textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'fonts/Quicksand-Medium.ttf',
fontSize: 18,
)),
(GestureDetector(onTap: () => Navigator.push(
context,
MaterialPageRoute(builder: (context) => analgesicos()),
)
),
child: const Material(
child: (
Card(
child: ListTile(
title: const Text('Analgésicos'),),)
),
),
),
const Material(
child: (
Card(
child: ListTile(
title: const Text('Anti-inflamatórios'),
),
)
),
),
const Material(
child: (
Card(
child: ListTile(
title: const Text('Antibióticos'),
),
)
),
),
const Material(
child: (
Card(
child: ListTile(
title: const Text('Antifúngicos'),
),
)
),
),
const Material(
child: (
Card(
child: ListTile(
title: const Text('Antivirais'),
),
)
),
),
const Material(
child: (
Card(
child: ListTile(
title: const Text('Anti-histamínicos'),
),
)
),
),
const Material(
child: (
Card(
child: ListTile(
title: const Text('Ansiolíticos'),
),
)
),
)
]
),
),
);
}
}
There is a parenthesis issue on GestureDetector
closing,
GestureDetector(
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => analgesicos(),
),
), // issue was here
child: const Material(
child: Card(
child: ListTile(
title: const Text('Analgésicos'),
),
),
),
),
use below snippet
class _HomePageState extends State<HomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.teal,
centerTitle: true,
title: Text(
'Farmacologia Odontológica',
style: TextStyle(
fontFamily: 'fonts/Quicksand-Light.ttf',
fontSize: 22,
),
),
),
body: Container(
child:
Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
Padding(
padding: const EdgeInsets.only(top: 10, bottom: 10),
),
Text('Classes de Medicamentos',
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'fonts/Quicksand-Medium.ttf',
fontSize: 18,
)),
GestureDetector(
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => analgesicos(),
),
), // issue was here
child: const Material(
child: Card(
child: ListTile(
title: const Text('Analgésicos'),
),
),
),
),
GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => analgesicos(),
),
);
},
child: Card(
child: ListTile(
title: const Text('Anti-inflamatórios'),
),
),
),
InkWell(
onLongPress: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => analgesicos(),
),
);
},
child: Card(
child: ListTile(
title: const Text('Antibióticos'),
),
),
),
Card(
child: ListTile(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => analgesicos(),
),
);
},
title: const Text('Antifúngicos'),
),
),
const Material(
child: (Card(
child: ListTile(
title: const Text('Antivirais'),
),
)),
),
const Material(
child: (Card(
child: ListTile(
title: const Text('Anti-histamínicos'),
),
)),
),
const Material(
child: (Card(
child: ListTile(
title: const Text('Ansiolíticos'),
),
)),
)
]),
),
);
}
}
I've included 3 ways of using tap event
GestureDetector
InkWell
ListTile's onTap

How to access ThemeData from imported widgets

I can not use the ThemeData from the imported custom Widgets that I have imported from other files, I dont know if the BuildContext is changing or what. To all the widgets that are used in the main.dart file they can easily use Theme.of(context).colorScheme.primary but from imported widgets this does not work.
main.dart
import 'package:flutter/material.dart';
import 'widgets/expenses_list.dart';
import 'models/expenses_model.dart';
import 'widgets/new_expense.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData().copyWith(
colorScheme: ThemeData().colorScheme.copyWith(primary: Colors.red),
),
home: MyAppPage(),
);
}
}
class MyAppPage extends StatefulWidget {
#override
_MyAppPageState createState() => _MyAppPageState();
}
class _MyAppPageState extends State<MyAppPage> {
final List<ExpensesModel> _expensesObjectList = [
ExpensesModel(
id: DateTime.now().toString(),
name: "Shoes",
amount: 1200,
date: DateTime.now(),
),
ExpensesModel(
id: DateTime.now().toString(),
name: "Gun",
amount: 120000,
date: DateTime.now(),
),
];
void _addExpense(String exTitle, double exAmount) {
final _addExpenseObject = ExpensesModel(
id: DateTime.now().toString(),
name: exTitle,
amount: exAmount,
date: DateTime.now(),
);
setState(() {
_expensesObjectList.add(_addExpenseObject);
});
}
void _startAddNewExpense(BuildContext context) {
showModalBottomSheet(
context: context,
builder: (bcontext) {
return NewExpense(_addExpense);
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.primary,
// HERE IT DOES WORK
title: Text(
"Expense App",
// style: Theme.of(context).textTheme.title,
),
actions: [
IconButton(
onPressed: () {
_startAddNewExpense(context);
},
icon: Icon(Icons.add),
),
],
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Card(
elevation: 5,
color: Theme.of(context).colorScheme.primary,
// HERE IT DOES WORK
child: Text("CHART!!"),
),
ExpensesList(_expensesObjectList), //THE IMPORTED WIDGET
],
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: FloatingActionButton(
onPressed: () {
_startAddNewExpense(context);
},
child: Icon(Icons.add),
),
),
);
}
}
imported widget
import 'package:flutter/material.dart';
import '../models/expenses_model.dart';
class ExpensesList extends StatelessWidget {
final List<ExpensesModel> expensesObjectList;
ExpensesList(this.expensesObjectList);
#override
Widget build(BuildContext context) {
return Container(
height: 600,
child: ListView.builder(
itemBuilder: (context, index) {
return Card(
elevation: 5,
child: Row(
children: [
Container(
padding: EdgeInsets.symmetric(
vertical: 10,
horizontal: 10,
),
margin: EdgeInsets.all(10),
decoration: BoxDecoration(
border: Border.all(
color: Theme.of(context).colorScheme.primary,
// HERE IT DOES NOT WORK
width: 2,
),
),
child: Text(
"PKR ${expensesObjectList[index].amount}",
style: TextStyle(
color: Theme.of(context).colorScheme.primary,
// HERE IT DOES NOT WORK
fontWeight: FontWeight.bold,
),
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"${expensesObjectList[index].name}",
style:
TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
Text(
DateTime.now().toString(),
style: TextStyle(
color: Colors.grey,
),
),
],
),
],
),
);
},
itemCount: expensesObjectList.length,
),
);
}
}
Screenshot of the app
as you can see the border and text aren't using the theme-defined color which is red.
You can access the ThemeData of your app by following.
Color color = Theme.of(context).primaryColor;
I think unnecessary "MaterialApp" of "build" in "class _MyAppPageState", like this.
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.primary,
// HERE IT DOES WORK
title: Text(
"Expense App",
// style: Theme.of(context).textTheme.title,
),
actions: [
IconButton(
onPressed: () {
_startAddNewExpense(context);
},
icon: Icon(Icons.add),
),
],
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Card(
elevation: 5,
color: Theme.of(context).colorScheme.primary,
// HERE IT DOES WORK
child: Text("CHART!!"),
),
ExpensesList(_expensesObjectList), //THE IMPORTED WIDGET
],
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: FloatingActionButton(
onPressed: () {
_startAddNewExpense(context);
},
child: Icon(Icons.add),
),
);
}
If you really need to "MaterialApp" of "class _MyAppPageState", I think you can add theme property, like this.
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: Theme.of(context), // <- add this line.
home: Scaffold(
By the way, why won't you use primarySwatch?
How about this?
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.red,
),
home: MyAppPage(),
);
}
}

CupertinoDatePicker A RenderFlex overflowed by Infinity pixels on the bottom

I try to add a row of cancel and done button above the CupertinoDatePicker inside the Container but however hit error, what could possible go wrong?
════════ Exception caught by rendering library ═════════════════════════════════
A RenderFlex overflowed by Infinity pixels on the bottom.
The relevant error-causing widget was
Column
String _selectedDueDate;
var formatter = new DateFormat('dd-MM-yyyy');
ListTile(
leading: const Icon(Icons.today),
title: const Text('Due Date*'),
subtitle: _selectedDueDate
onTap: () {
showCupertinoModalPopup(
context: context,
builder: (context) {
return Container(
color: Colors.white,
height: 300.0,
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
FlatButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.zero),
child: Text(
"Cancel",
),
onPressed: () => {},
),
FlatButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.zero),
child: Text(
"Done",
),
onPressed: () => {},
),
],
),
CupertinoDatePicker(
initialDateTime:
DateTime.now().add(new Duration(days: 7)),
minimumDate: DateTime.now(),
mode: CupertinoDatePickerMode.date,
onDateTimeChanged: (date) {
setState(() {
print(date);
_selectedDueDate = formatter.format(date);
});
},
),
],
),
);
});
},
),
You can copy paste run full code below
You can wrap CupertinoDatePicker with Flexible
code snippet
Flexible(
child: CupertinoDatePicker(
working demo
full code
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
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> {
String _selectedDueDate;
var formatter = new DateFormat('dd-MM-yyyy');
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: ListTile(
leading: const Icon(Icons.today),
title: const Text('Due Date*'),
subtitle: Text("$_selectedDueDate"),
onTap: () {
showCupertinoModalPopup(
context: context,
builder: (context) {
return Container(
color: Colors.white,
height: 300.0,
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
FlatButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.zero),
child: Text(
"Cancel",
),
onPressed: () => {},
),
FlatButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.zero),
child: Text(
"Done",
),
onPressed: () => {},
),
],
),
Flexible(
child: CupertinoDatePicker(
initialDateTime:
DateTime.now().add(new Duration(days: 7)),
minimumDate: DateTime.now(),
mode: CupertinoDatePickerMode.date,
onDateTimeChanged: (date) {
setState(() {
print(date);
_selectedDueDate = formatter.format(date);
});
},
),
),
],
),
);
});
},
),
);
}
}
Wrap CupertinoDatePicker in a Container and set the desired height.

Flutter variable doesn't change background color when changed?

I'm new to flutter and am trying to update the background color of a scaffold when a variable is changed. the variable is declared in another file. The reason why it needs to change? I am trying to change the background of the app to grey, a dark mode option. Any advice on why the background doesn't change when the variable does? Any advice would be appreciated, thanks!
import 'package:flutter/material.dart';
import 'package:page_transition/page_transition.dart';
import 'package:share/share.dart';
import './Widgets/DrawerSettings.dart';
void main() {
runApp(MaterialApp(
title: 'Navigation Basics',
home: FirstRoute(),
));
}
class FirstRoute extends StatefulWidget {
#override
_FirstRouteState createState() => _FirstRouteState();
}
class _FirstRouteState extends State<FirstRoute> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
drawer: Container(
width: 70,
child: ClipRRect(
borderRadius: BorderRadius.vertical(top: Radius.circular(.0)),
child: Drawer(
child: Padding(
padding: const EdgeInsets.fromLTRB(0, 30, 0, 0),
child: Column(
children: <Widget>[
IconButton(
icon: Icon(Icons.bookmark),
onPressed: () {
Navigator.push(
context,
PageTransition(
type: PageTransitionType.rightToLeft,
child: SavedRoute()));
},
),
IconButton(
icon: Icon(Icons.rate_review),
onPressed: () {
Navigator.push(
context,
PageTransition(
type: PageTransitionType.rightToLeft,
child: ReviewRoute()));
},
),
IconButton(
icon: Icon(Icons.share),
onPressed: () {
Share.share('Share');
},
),
IconButton(
icon: Icon(Icons.settings),
onPressed: () {
Navigator.push(
context,
PageTransition(
type: PageTransitionType.rightToLeft,
child: SettingsRoute()));
},
)
],
),
),
),
),
),
appBar: AppBar(
title: Text(
'Explore',
),
centerTitle: true,
backgroundColor: Colors.cyan[500],
),
body: Scaffold(
backgroundColor: DarkMode ? Colors.grey[800] : Colors.white, //Here is the code to change the background color when variable change.
body: Padding(
padding: const EdgeInsets.fromLTRB(2, 12, 2, 12),
child: Center(
child: ListView(
shrinkWrap: true,
padding: EdgeInsets.all(5.0),
children: <Widget>[
Column(
children: [
Container(
padding: EdgeInsets.fromLTRB(2, 10, 2, 0),
height: 150,
width: double.maxFinite,
child: InkWell(
onTap: () {
Navigator.push(
context,
PageTransition(
type: PageTransitionType.rightToLeft,
child: SecondRoute()));
},
child: Card(
elevation: 5,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
child: ClipRRect(
borderRadius: BorderRadius.circular(15.0),
child: Image.network(
'https://i.ytimg.com/vi/hlWiI4xVXKY/maxresdefault.jpg',
fit: BoxFit.cover,
height: 150.0,
width: 100.0,
),
),
),
),
),
],
),
),
),
),
),
);
}
}
Here is the second file
import 'package:flutter/material.dart';
class SettingsRoute extends StatefulWidget {
#override
_SettingsRouteState createState() => _SettingsRouteState();
}
bool DarkMode = false;
class _SettingsRouteState extends State<SettingsRoute> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: DarkMode ? Colors.grey[800] : Colors.white,
appBar: AppBar(
title: Text(
'Settings',
),
centerTitle: true,
),
body: ListView(
children: <Widget>[
Container(
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 20, 10, 20),
child: SwitchListTile(
title: Text(
'Dark Mode',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w400,
color: DarkMode ? Colors.white : Colors.grey[800],
),
),
value: DarkMode,
activeColor: Colors.white,
inactiveThumbColor: Colors.white,
onChanged: (bool value) {
setState(() {
DarkMode = !DarkMode;
});
},
),
),
),
],
),
),
);
}
}
You can copy paste run full code below
You can pass callback refresh to SettingsRoute and call with widget.callback()
You can see working demo below
code snippet
class _FirstRouteState extends State<FirstRoute> {
refresh() {
setState(() {});
}
...
onPressed: () {
Navigator.push(
context,
PageTransition(
type: PageTransitionType.rightToLeft,
child: SettingsRoute(
callback: refresh,
)));
},
...
class SettingsRoute extends StatefulWidget {
final VoidCallback callback;
SettingsRoute({this.callback});
...
onChanged: (bool value) {
setState(() {
DarkMode = !DarkMode;
});
widget.callback();
},
working demo
full code
import 'package:flutter/material.dart';
import 'package:page_transition/page_transition.dart';
import 'package:share/share.dart';
void main() {
runApp(MaterialApp(
title: 'Navigation Basics',
home: FirstRoute(),
));
}
class FirstRoute extends StatefulWidget {
#override
_FirstRouteState createState() => _FirstRouteState();
}
class _FirstRouteState extends State<FirstRoute> {
refresh() {
setState(() {});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
drawer: Container(
width: 70,
child: ClipRRect(
borderRadius: BorderRadius.vertical(top: Radius.circular(.0)),
child: Drawer(
child: Padding(
padding: const EdgeInsets.fromLTRB(0, 30, 0, 0),
child: Column(
children: <Widget>[
IconButton(
icon: Icon(Icons.bookmark),
onPressed: () {
/* Navigator.push(
context,
PageTransition(
type: PageTransitionType.rightToLeft,
child: SavedRoute()));*/
},
),
IconButton(
icon: Icon(Icons.rate_review),
onPressed: () {
/* Navigator.push(
context,
PageTransition(
type: PageTransitionType.rightToLeft,
child: ReviewRoute()));*/
},
),
IconButton(
icon: Icon(Icons.share),
onPressed: () {
Share.share('Share');
},
),
IconButton(
icon: Icon(Icons.settings),
onPressed: () {
Navigator.push(
context,
PageTransition(
type: PageTransitionType.rightToLeft,
child: SettingsRoute(
callback: refresh,
)));
},
)
],
),
),
),
),
),
appBar: AppBar(
title: Text(
'Explore',
),
centerTitle: true,
backgroundColor: Colors.cyan[500],
),
body: Scaffold(
backgroundColor: DarkMode
? Colors.grey[800]
: Colors
.white, //Here is the code to change the background color when variable change.
body: Padding(
padding: const EdgeInsets.fromLTRB(2, 12, 2, 12),
child: Center(
child: ListView(
shrinkWrap: true,
padding: EdgeInsets.all(5.0),
children: <Widget>[
Column(
children: [
Container(
padding: EdgeInsets.fromLTRB(2, 10, 2, 0),
height: 150,
width: double.maxFinite,
child: InkWell(
onTap: () {
/* Navigator.push(
context,
PageTransition(
type: PageTransitionType.rightToLeft,
child: SecondRoute()));*/
},
child: Card(
elevation: 5,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
child: ClipRRect(
borderRadius: BorderRadius.circular(15.0),
child: Image.network(
'https://i.ytimg.com/vi/hlWiI4xVXKY/maxresdefault.jpg',
fit: BoxFit.cover,
height: 150.0,
width: 100.0,
),
),
),
),
),
],
),
]),
),
),
),
));
}
}
class SettingsRoute extends StatefulWidget {
final VoidCallback callback;
SettingsRoute({this.callback});
#override
_SettingsRouteState createState() => _SettingsRouteState();
}
bool DarkMode = false;
class _SettingsRouteState extends State<SettingsRoute> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: DarkMode ? Colors.grey[800] : Colors.white,
appBar: AppBar(
title: Text(
'Settings',
),
centerTitle: true,
),
body: ListView(
children: <Widget>[
Container(
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 20, 10, 20),
child: SwitchListTile(
title: Text(
'Dark Mode',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w400,
color: DarkMode ? Colors.white : Colors.grey[800],
),
),
value: DarkMode,
activeColor: Colors.white,
inactiveThumbColor: Colors.white,
onChanged: (bool value) {
setState(() {
DarkMode = !DarkMode;
});
widget.callback();
},
),
),
),
],
),
),
);
}
}
You need to get the value of the DarkMode variable from a global variable like using an app state provider. Or you can send the DarkMode value as a parameter to the next page. The first one is a better use-case.
Your provider will look like this:
import 'package:flutter/material.dart';
class AppStateProvider with ChangeNotifier {
bool _darkMode = false;
bool get darkMode => this._darkMode;
void setDarkMode(bool value) {
this._darkMode = value;
}
}
You can read more from here.