I am completely new to Flutter and I have this screen that uses bottomSheet and I want to go to a new screen when I click on a project, while staying inside this parent screen that has the bottomSheet in it. Here is the source code for the parent screen and the Projects screen inside it.
Parent Main Menu screen
import 'package:flutter/material.dart';
import 'projects.dart';
import 'app-bar.dart';
class MainMenu extends StatefulWidget {
#override
_MainMenuState createState() => _MainMenuState();
}
class _MainMenuState extends State<MainMenu> {
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
int _selectedIndex = 0;
static List<TabItem> _widgetOptions = <TabItem>[
TabItem(
text: new Text('Projects'),
className: Projects(),
),
TabItem(
text: new Text('Organization'),
className: null,
),
TabItem(
text: new Text('Profile'),
className: null,
),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: SafeArea(
child: new DefaultTabController(
length: 3,
child: new Scaffold(
key: _scaffoldKey,
appBar: appBar(_widgetOptions.elementAt(_selectedIndex).text),
body: _widgetOptions.elementAt(_selectedIndex).className,
bottomNavigationBar: BottomNavigationBar(
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.view_column),
label: 'Projects'
),
BottomNavigationBarItem(
icon: Icon(Icons.people),
label: 'Organization'
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
label: 'Profile'
)
],
currentIndex: _selectedIndex,
onTap: _onItemTapped,
),
),
)
),
);
}
}
class TabItem {
Widget text;
dynamic className;
TabItem({ #required this.text, #required this.className });
}
Projects
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pmtool/project-page.dart';
import './interfaces/iprojects.dart';
import './constants/route-names.dart';
class Projects extends StatefulWidget {
#override
_ProjectsState createState() => _ProjectsState();
}
class _ProjectsState extends State<Projects> {
final GlobalKey<ScaffoldState> _scaffoldState = new GlobalKey<ScaffoldState>();
static const List<Text> sortOptions = [
Text('Project Name'),
Text('Project Number'),
Text('Client Name'),
Text('Percent Completed'),
Text('Date Added'),
Text('Project Type'),
];
static const List<String> sortOrder = [
'Descending',
'Ascending',
];
static const List<String> filters = [
'Ongoing',
'All',
'Completed',
];
List<bool> isSelected = [
true, false, false, false, false, false,
];
String selectedSort = 'Descending';
static List<ProjectsMock> projects = [
ProjectsMock(projectId: '1', projectNumber: '1', projectName: 'Project 1', clientName: 'asd', projectStatus: 'Ongoing'),
ProjectsMock(projectId: '2', projectNumber: '2', projectName: 'Project 2', clientName: 'qwe', projectStatus: 'Completed'),
];
String selectedFilter = 'Ongoing';
void selectItem(int index) {
setState(() {
for (int i = 0; i < isSelected.length; i++) {
if (i != index) {
isSelected[i] = false;
return;
}
isSelected[i] = true;
}
});
}
void navigateToProject(BuildContext context, ProjectsMock project) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProjectPage(),
settings: RouteSettings(
arguments: project,
)
)
);
}
void setBottomSheet(context) {
showModalBottomSheet(
context: context,
builder: (BuildContext buildContext) {
return Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Text('Filters', style: TextStyle(fontWeight: FontWeight.bold),),
new Wrap(
spacing: 5.0,
children: List.generate(filters.length, (index) {
if (selectedFilter == filters.elementAt(index)) {
return new ActionChip(
label: new Text(filters.elementAt(index)),
backgroundColor: Colors.blue,
labelStyle: TextStyle(color: Colors.white),
onPressed: () {
return;
},
);
}
return new ActionChip(
label: new Text(filters.elementAt(index)),
backgroundColor: Colors.white,
labelStyle: TextStyle(color: Colors.blue),
onPressed: () {
return;
},
);
}),
),
new Text('Sort by', style: TextStyle(fontWeight: FontWeight.bold),),
new Wrap(
spacing: 5.0,
children: List.generate(sortOptions.length, (index) {
if (isSelected[index]) {
return new ActionChip(
label: sortOptions.elementAt(index),
backgroundColor: Colors.blue,
labelStyle: TextStyle(color: Colors.white),
onPressed: () {
return;
},
);
}
return new ActionChip(
label: sortOptions.elementAt(index),
backgroundColor: Colors.white,
labelStyle: TextStyle(color: Colors.blue),
onPressed: () {
return;
},
);
}),
),
new Container(
margin: const EdgeInsets.only(top: 10.0),
child: new Text('Sort Order', style: TextStyle(fontWeight: FontWeight.bold),),
),
new Wrap(
spacing: 5.0,
children: List.generate(sortOrder.length, (index) {
if (selectedSort == sortOrder[index]) {
return new ActionChip(
label: Text(sortOrder.elementAt(index)),
backgroundColor: Colors.blue,
labelStyle: TextStyle(color: Colors.white),
onPressed: () {
return;
},
);
}
return new ActionChip(
label: Text(sortOrder.elementAt(index)),
backgroundColor: Colors.white,
labelStyle: TextStyle(color: Colors.blue),
onPressed: () {
return;
},
);
}),
),
],
),
);
}
);
}
#override
Widget build(BuildContext context) {
return new Scaffold(
floatingActionButton: new FloatingActionButton(child: new Icon(Icons.filter_alt), onPressed: () => setBottomSheet(context), mini: true),
key: _scaffoldState,
body: new Column(
children: <Widget>[
new Expanded(
child: new Column(
children: <Widget>[
// Search header
new Container(
padding: const EdgeInsets.all(10.0),
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Expanded(
child: new TextField(
decoration: new InputDecoration(
hintText: 'Search',
labelText: 'Search',
suffixIcon: new IconButton(icon: Icon(Icons.search), onPressed: () {
return;
}),
contentPadding: const EdgeInsets.only(left: 5.0, right: 5.0)
),
)
),
],
),
],
),
),
new Padding(
padding: const EdgeInsets.only(left: 10.0, right: 10.0),
child: new Column(
children: List.generate(projects.length, (index) {
return new Container(
margin: const EdgeInsets.only(bottom: 10.0),
child: new RaisedButton(
onPressed: () => navigateToProject(context, projects.elementAt(index)),
color: Colors.white,
textColor: Colors.black,
child: new Padding(
padding: const EdgeInsets.all(10.0),
child: new Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
new Expanded(
child: new Column(
children: <Widget>[
new Text(projects.elementAt(index)?.projectName, style: TextStyle(fontWeight: FontWeight.bold)),
new Text(projects.elementAt(index)?.projectNumber),
]
),
),
new Expanded(
child: new Column(
children: <Widget>[
new Text(projects.elementAt(index)?.clientName, style: TextStyle(fontWeight: FontWeight.bold)),
new Text(projects.elementAt(index)?.projectStatus),
]
),
)
],
),
),
),
);
}),
),
)
],
),
)
],
),
);
}
}
Here is a snapshot of the page.
How do I do it? I tried using Navigator but it goes to a completely new screen. Let me know if you need more information.
You create another inside your main.dart file and use Navigator to move to that screen without actually moving to another screen instead replacing the current one
this is how the code goes
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DisplayPictureScreen(string1: string),//passing a parameter
),
);
and this how the class goes
class DisplayPictureScreen extends StatelessWidget {
final String string1;
const DisplayPictureScreen({Key key, this.string1}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(value[0]["label"],style: TextStyle(color: Colors.black,fontSize: 20),
)),
body: Column(
children: [
Text("lsfnklsnlvfdngvlirs")
],
),
);
}
}
Related
I tried to create a task app using flutter, So I created a text field in DialogBox and my aim is when I add some text into the text field and when I clicked the OK button, I need to show that text in the list. but I have no idea how to call a method in another class, I've added my two classes.
ListTask Class
import 'package:flutter/material.dart';
class ListTask extends StatefulWidget {
const ListTask({Key? key}) : super(key: key);
#override
State<ListTask> createState() => _ListTaskState();
}
class _ListTaskState extends State<ListTask> {
final List<String> tasks = ['masu', 'adasf', 'wfqf', 'santha'];
final TextEditingController _textFieldController = TextEditingController();
void addItemToList() {
setState(() {
tasks.insert(0, _textFieldController.text);
});
}
#override
Widget build(BuildContext context) {
return Container(
height: 320,
width: double.maxFinite,
child: ListView.builder(
padding: EdgeInsets.only(bottom: 10),
itemCount: tasks.length,
itemBuilder: (context, index) {
return Card(
elevation: 1,
color: Colors.grey[200],
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ExpansionTile(title: Text(tasks[index]), children: <Widget>[
ListTile(
title: Text(tasks[index]),
)
]),
],
),
);
},
),
);
}
Future<void> _displayTextInputDialog(BuildContext context) async {
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('TextField in Dialog'),
content: TextField(
onChanged: (value) {
setState(() {
// valueText = value;
});
},
controller: _textFieldController,
decoration: InputDecoration(hintText: "Text Field in Dialog"),
),
actions: <Widget>[
FlatButton(
color: Colors.red,
textColor: Colors.white,
child: Text('CANCEL'),
onPressed: () {
setState(() {
Navigator.pop(context);
});
},
),
FlatButton(
color: Colors.green,
textColor: Colors.white,
child: Text('OK'),
onPressed: () {
setState(() {
addItemToList();
Navigator.pop(context);
});
},
),
],
);
});
}
}
TaskApp Class
import 'package:flutter/material.dart';
import 'package:task_app/Widgets/listtasks.dart';
import 'package:task_app/Widgets/logo.dart';
import 'package:task_app/Widgets/searchbar.dart';
class TaskApp extends StatefulWidget {
const TaskApp({Key? key}) : super(key: key);
#override
State<TaskApp> createState() => _TaskAppState();
}
class _TaskAppState extends State<TaskApp> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(15.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(height: 10),
Logo(),
SizedBox(height: 0),
SearchBar(),
SizedBox(height: 15),
Column(
children: [
Text(
'All tasks',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15.0),
)
],
),
SizedBox(height: 15),
ListTask(),
],
),
),
floatingActionButton: FloatingActionButton.extended(
onPressed: () {
_displayTextInputDialog(context);
},
label: const Text('Add Task'),
icon: const Icon(Icons.add),
backgroundColor: Colors.blue[900],
),
);
}
}
Calling point of that method in TaskApp Class:
Method:
You can give this a try, it will call a method defined in ListTask(StatefulWidget) from TaskApp(StatefulWidget) widget.
TaskApp.dart
import 'package:flutter/material.dart';
import 'package:vcare/Screens/tetxing1.dart';
class TaskApp extends StatefulWidget {
final ListTask listTask;
const TaskApp({Key? key,required this.listTask}) : super(key: key);
#override
State<TaskApp> createState() => _TaskAppState();
}
class _TaskAppState extends State<TaskApp> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(15.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(height: 10),
// Logo(),
SizedBox(height: 0),
//SearchBar(),
SizedBox(height: 15),
Column(
children: [
Text(
'All tasks',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15.0),
)
],
),
SizedBox(height: 15),
ListTask(),
],
),
),
floatingActionButton: FloatingActionButton.extended(
onPressed: () {
ListTask().method1(context);
},
label: const Text('Add Task'),
icon: const Icon(Icons.add),
backgroundColor: Colors.blue[900],
),
);
}
}
ListTask.dart
import 'package:flutter/material.dart';
class ListTask extends StatefulWidget {
method1(context) => createState().displayTextInputDialog(context);
#override
_ListTaskState createState() => _ListTaskState();
}
class _ListTaskState extends State<ListTask> {
final List<String> tasks = ['masu', 'adasf', 'wfqf', 'santha'];
final TextEditingController _textFieldController = TextEditingController();
void addItemToList() {
setState(() {
tasks.insert(0, _textFieldController.text);
});
}
#override
Widget build(BuildContext context) {
return Container(
height: 320,
width: double.maxFinite,
child: ListView.builder(
padding: EdgeInsets.only(bottom: 10),
itemCount: tasks.length,
itemBuilder: (context, index) {
return Card(
elevation: 1,
color: Colors.grey[200],
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ExpansionTile(title: Text(tasks[index]), children: <Widget>[
ListTile(
title: Text(tasks[index]),
)
]),
],
),
);
},
),
);
}
Future<void> displayTextInputDialog(BuildContext context) async {
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('TextField in Dialog'),
content: TextField(
onChanged: (value) {
setState(() {
// valueText = value;
});
},
controller: _textFieldController,
decoration: InputDecoration(hintText: "Text Field in Dialog"),
),
actions: <Widget>[
FlatButton(
color: Colors.red,
textColor: Colors.white,
child: Text('CANCEL'),
onPressed: () {
setState(() {
Navigator.pop(context);
});
},
),
FlatButton(
color: Colors.green,
textColor: Colors.white,
child: Text('OK'),
onPressed: () {
setState(() {
addItemToList();
Navigator.pop(context);
});
},
),
],
);
});
}
}
if you find this solution helpful please mark as accepted answer
I need to rebuild my listview because it is only maintaining the first build, unless I reset the app. I have a bottom sheet pop up that lets me select times and navigate me to a new page where the listview.builder builds. If I back out of the page, select new options, and go back into the page, it does not update. Here is an example:
Relevant Code:
final selectTimesTextStyle = TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
);
final List classBools = [
checkedPreBallet,
checkedBeginningBallet,
checkedIntermediateBallet,
checkedAdvancedBallet,
checkedJazz,
checkedPC,
];
final List<String> preballetItems = [
'Wednesday 3:00-4:00',
'Friday 3:00-3:35',
];
final List<String> privateClassesItems = [
'Mondays, Schedule Via Email',
];
final List<String> intermediateBalletItems = [
'Tuesday 5:00-6:00',
'Thursday 5:00-6:00',
'Saturday 10:00-11:00',
];
final List<String> advancedBalletItems = [
'Tuesday 6:00-7:00',
'Thursday 6:00-7:00',
];
final List<String> beginningBalletItems = [
'Wednesday 3:45-4:45',
'Friday 3:45-4:45',
];
final List<String> jazzItems = [
'Thursday 4:00-5:00',
];
final List<List> listOfLists = [
preballetItems,
beginningBalletItems,
intermediateBalletItems,
advancedBalletItems,
jazzItems,
privateClassesItems,
];
List<String> valueChoose = [
'Wednesday 3:00-4:00',
'Wednesday 3:45-4:45',
'Tuesday 5:00-6:00',
'Tuesday 6:00-7:00',
'Thursday 4:00-5:00',
'Mondays, Schedule Via Email',
];
class TimeSelection extends StatelessWidget {
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: InkWell(
onTap: () => {
Navigator.of(context).pop(),
currentIndex = 2,
checkedPreBallet = false,
checkedBeginningBallet = false,
checkedIntermediateBallet = false,
checkedAdvancedBallet = false,
checkedJazz = false,
checkedPC = false,
},
child: Container(
child: Icon(Icons.arrow_back),
),
),
title: Text('Select Times'),
centerTitle: true,
),
body: StatefulBuilder(
builder: (context, setState) => Column(
children: [
Expanded(
child: ListView.builder(
itemCount: 6,
itemBuilder: (context, index) => Visibility(
maintainState: false,
visible: classBools[index],
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
child: Text(
buttonTitles[index],
style: selectTimesTextStyle,
),
width: MediaQuery.of(context).size.width * 0.50,
),
Container(
width: MediaQuery.of(context).size.width * 0.40,
child: DropdownButton(
isExpanded: true,
underline: SizedBox(),
dropdownColor: Colors.white,
value: valueChoose[index],
onChanged: (newValue) => {
setState(() {
valueChoose[index] = newValue;
})
},
items: listOfLists[index]
.map((e) => DropdownMenuItem(
onTap: () => {
classBools[index] = true,
},
child: Text(e),
value: e,
))
.toList(),
),
),
],
),
),
),
),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 120,
vertical: 15,
),
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
stops: [
0.00005,
1,
],
colors: [
Theme.of(context).secondaryHeaderColor,
Theme.of(context).primaryColor,
]),
boxShadow: [
BoxShadow(color: Colors.black54, offset: Offset(3, 3)),
],
color: Colors.purpleAccent,
borderRadius: BorderRadius.circular(15),
),
child: InkWell(
onTap: () => {},
child: Padding(
padding: EdgeInsets.all(16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text('PayPal'),
],
),
),
),
),
),
],
),
),
);
}
}
bool checkedPreBallet = false;
bool checkedBeginningBallet = false;
bool checkedIntermediateBallet = false;
bool checkedAdvancedBallet = false;
bool checkedJazz = false;
bool checkedPC = false;
final List<String> buttonTitles = [
'Pre-Ballet',
'Beginning Ballet',
'Intermediate Ballet',
'Advanced Ballet',
'Jazz',
'Private Classes',
];
class RegisterPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Divider(),
Text('hello'),
Divider(),
RegisterCards(),
],
),
);
}
}
class RegisterCards extends StatefulWidget {
#override
_RegisterCardsState createState() => _RegisterCardsState();
}
class _RegisterCardsState extends State<RegisterCards> {
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: 30,
),
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
stops: [
0.00005,
1,
],
colors: [
Theme.of(context).secondaryHeaderColor,
Theme.of(context).primaryColor,
]),
boxShadow: [
BoxShadow(color: Colors.black54, offset: Offset(3, 3)),
],
color: Colors.purpleAccent,
borderRadius: BorderRadius.circular(15),
),
child: InkWell(
onTap: () => onButtonPressed(context),
child: Padding(
padding: EdgeInsets.all(16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text('Register Here'),
],
),
),
),
),
);
}
}
class ClassListWidget extends StatefulWidget {
#override
_ClassListWidgetState createState() => _ClassListWidgetState();
}
class _ClassListWidgetState extends State<ClassListWidget> {
#override
Widget build(BuildContext context) {
return StatefulBuilder(
builder: (context, setState) => Column(
children: [
CheckboxListTile(
value: checkedPreBallet,
onChanged: (value) => {
setState(() {
checkedPreBallet = value;
})
},
title: Text('Pre-Ballet'),
checkColor: Theme.of(context).scaffoldBackgroundColor,
activeColor: Theme.of(context).primaryColor,
secondary: Icon(PokemonIcons.i004_charmander),
controlAffinity: ListTileControlAffinity.leading,
tristate: false,
),
CheckboxListTile(
value: checkedBeginningBallet,
onChanged: (value) => {
setState(() {
checkedBeginningBallet = value;
})
},
title: Text('Beginning Ballet'),
checkColor: Theme.of(context).scaffoldBackgroundColor,
activeColor: Theme.of(context).primaryColor,
secondary: Icon(PokemonIcons.i004_charmander),
controlAffinity: ListTileControlAffinity.leading,
tristate: false,
),
CheckboxListTile(
value: checkedIntermediateBallet,
onChanged: (value) => {
setState(() {
checkedIntermediateBallet = value;
})
},
title: Text('Intermediate Ballet'),
checkColor: Theme.of(context).scaffoldBackgroundColor,
activeColor: Theme.of(context).primaryColor,
secondary: Icon(PokemonIcons.i004_charmander),
controlAffinity: ListTileControlAffinity.leading,
tristate: false,
),
CheckboxListTile(
value: checkedAdvancedBallet,
onChanged: (value) => {
setState(() {
checkedAdvancedBallet = value;
})
},
title: Text('Advanced Ballet'),
checkColor: Theme.of(context).scaffoldBackgroundColor,
activeColor: Theme.of(context).primaryColor,
secondary: Icon(PokemonIcons.i004_charmander),
controlAffinity: ListTileControlAffinity.leading,
tristate: false,
),
CheckboxListTile(
value: checkedJazz,
onChanged: (value) => {
setState(() {
checkedJazz = value;
})
},
title: Text('Jazz'),
checkColor: Theme.of(context).scaffoldBackgroundColor,
activeColor: Theme.of(context).primaryColor,
secondary: Icon(PokemonIcons.i004_charmander),
controlAffinity: ListTileControlAffinity.leading,
tristate: false,
),
CheckboxListTile(
value: checkedPC,
onChanged: (value) => {
setState(() {
checkedPC = value;
})
},
title: Text('Private Classes'),
checkColor: Theme.of(context).scaffoldBackgroundColor,
activeColor: Theme.of(context).primaryColor,
secondary: Icon(PokemonIcons.i004_charmander),
controlAffinity: ListTileControlAffinity.leading,
tristate: false,
),
],
),
);
}
}
void onButtonPressed(context) {
showModalBottomSheet(
isScrollControlled: false,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(15),
topRight: Radius.circular(15),
),
),
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
context: context,
builder: (context) => StatefulBuilder(
builder: (BuildContext context, setState) => Container(
child: Column(
children: [
ClassListWidget(),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 15,
),
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
stops: [
0.00005,
1,
],
colors: [
Theme.of(context).secondaryHeaderColor,
Theme.of(context).primaryColor,
]),
boxShadow: [
BoxShadow(color: Colors.black54, offset: Offset(3, 3)),
],
color: Colors.purpleAccent,
borderRadius: BorderRadius.circular(15),
),
child: InkWell(
onTap: () => {
Navigator.push(context, MaterialPageRoute(
builder: (context) => TimeSelection(),
)),
},
child: Padding(
padding: EdgeInsets.all(14),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text('Select Times'),
],
),
),
),
),
),
],
),
),
),
);
}
check this out whether it fits your need.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: TimeSelection(),
);
}
}
// model class for your ballet
class Ballet {
final String balletName;
final List<String> timeSchedules;
final String description;
String selectedTime;
bool isSelected = false;
Ballet({
this.balletName,
this.timeSchedules,
isSelected,
this.description = '',
this.selectedTime
}) {selectedTime ??= this.timeSchedules[0];}
}
List<Ballet> balletItems = <Ballet>[
Ballet(
balletName: "Pre-Ballet",
timeSchedules: [
'Wednesday 3:00-4:00',
'Friday 3:00-3:35',
],
),
Ballet(
balletName: "Private Classes",
timeSchedules: [
'Mondays',
],
description: 'Scheduled Via Email'
),
Ballet(
balletName: "Intermediate Ballet",
timeSchedules: [
'Tuesday 5:00-6:00',
'Thursday 5:00-6:00',
'Saturday 10:00-11:00',
],
),
Ballet(
balletName: "Advance Ballet",
timeSchedules: [
'Tuesday 6:00-7:00',
'Thursday 6:00-7:00',
],
),
Ballet(
balletName: "Beginning Ballet",
timeSchedules: [
'Wednesday 3:45-4:45',
'Friday 3:45-4:45',
],
),
Ballet(
balletName: "Jazz Ballet",
timeSchedules: [
'Thursday 4:00-5:00',
],
)
];
class TimeSelection extends StatefulWidget {
#override
_TimeSelectionState createState() => _TimeSelectionState();
}
class _TimeSelectionState extends State<TimeSelection> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Center(
child: Column(
children: [
Text('hello there', style: Theme.of(context).textTheme.headline4),
ElevatedButton(child: Text('Register Here',), onPressed: () {},),
],
),
),
Expanded(
child: ListView.builder(
itemCount: balletItems.length+1 ,
itemBuilder: (context, index){
if (index < balletItems.length) {
Ballet balletItem = balletItems[index];
return ListTile(leading: Checkbox(
value: balletItem.isSelected,
onChanged: (value) {
setState((){
balletItem.isSelected = value;
});
},),
title: Text(balletItem.balletName),
trailing: Icon(Icons.auto_awesome),
);}
else{
return Container(
margin: const EdgeInsets.symmetric(horizontal: 20.0),
child: ElevatedButton(
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(builder: (context) => SelectTimes(),));
},
child: Text('Select Times'),
),
);}
},
),
)
],
),
drawer: Drawer(),
appBar: AppBar(title: Text("Class Registration"),),
);
}
}
class SelectTimes extends StatefulWidget {
#override
_SelectTimesState createState() => _SelectTimesState();
}
class _SelectTimesState extends State<SelectTimes> {
List<Ballet> selectedBalletItems;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Select Times'),),
body: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
children: [
Expanded(
child: ListView.builder(
itemCount: selectedBalletItems.length,
itemBuilder: (context, index) {
Ballet selectedBalletItem = selectedBalletItems[index];
return _listTile(selectedBalletItem);
},
),
),
ElevatedButton(child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text("PayPal", style: Theme.of(context).textTheme.headline4,
),
),
onPressed: () {},)
],
),
)
);
}
Widget _listTile(Ballet selectedBalletItem) {
return ListTile(
title: Text(selectedBalletItem.balletName),
subtitle: Text(selectedBalletItem.description , style: Theme.of(context).textTheme.bodyText2.copyWith(color: Colors.grey[500])),
trailing: DropdownButton<String>(
value: selectedBalletItem.selectedTime,
items: selectedBalletItem.timeSchedules.map((timeSchedule) {
return DropdownMenuItem(value: timeSchedule, child: Text(timeSchedule));
} ).toList(),
onChanged: (value) {
setState(() {
selectedBalletItem.selectedTime = value;
});
},
)
);
}
#override
void initState() {
super.initState();
selectedBalletItems = balletItems.where((e) => e.isSelected).toList();
}
}
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:image_picker/image_picker.dart';
import 'package:qrscan/qrscan.dart' as scanner;
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Uint8List bytes = Uint8List(0);
TextEditingController _inputController;
TextEditingController _outputController;
#override
initState() {
super.initState();
this._inputController = new TextEditingController();
this._outputController = new TextEditingController();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.grey[300],
body: Builder(
builder: (BuildContext context) {
return ListView(
children: <Widget>[
_qrCodeWidget(this.bytes, context),
Container(
color: Colors.white,
child: Column(
children: <Widget>[
TextField(
controller: this._inputController,
keyboardType: TextInputType.url,
textInputAction: TextInputAction.go,
onSubmitted: (value) => _generateBarCode(value),
decoration: InputDecoration(
prefixIcon: Icon(Icons.text_fields),
helperText: 'Please input your code to generage qrcode image.',
hintText: 'Please Input Your Code',
hintStyle: TextStyle(fontSize: 15),
contentPadding: EdgeInsets.symmetric(
horizontal: 7, vertical: 15),
),
),
SizedBox(height: 20),
TextField(
controller: this._outputController,
maxLines: 2,
decoration: InputDecoration(
prefixIcon: Icon(Icons.wrap_text),
helperText: 'The barcode or qrcode you scan will be displayed in this area.',
hintText: 'The barcode or qrcode you scan will be displayed in this area.',
hintStyle: TextStyle(fontSize: 15),
contentPadding: EdgeInsets.symmetric(
horizontal: 7, vertical: 15),
),
),
SizedBox(height: 20),
this._buttonGroup(),
SizedBox(height: 70),
],
),
),
],
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: () => _scanBytes(),
tooltip: 'Take a Photo',
child: const Icon(Icons.camera_alt),
),
),
);
}
Widget _qrCodeWidget(Uint8List bytes, BuildContext context) {
return Padding(
padding: EdgeInsets.all(20),
child: Card(
elevation: 6,
child: Column(
children: <Widget>[
Container(
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Icon(Icons.verified_user, size: 18, color: Colors.green),
Text(' Generate Qrcode', style: TextStyle(fontSize: 15)),
Spacer(),
Icon(Icons.more_vert, size: 18, color: Colors.black54),
],
),
padding: EdgeInsets.symmetric(horizontal: 10, vertical: 9),
decoration: BoxDecoration(
color: Colors.black12,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(4), topRight: Radius.circular(4)),
),
),
Padding(
padding: EdgeInsets.only(
left: 40, right: 40, top: 30, bottom: 10),
child: Column(
children: <Widget>[
SizedBox(
height: 190,
child: bytes.isEmpty
? Center(
child: Text('Empty code ... ',
style: TextStyle(color: Colors.black38)),
)
: Image.memory(bytes),
),
Padding(
padding: EdgeInsets.only(top: 7, left: 25, right: 25),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Expanded(
flex: 5,
child: GestureDetector(
child: Text(
'remove',
style: TextStyle(
fontSize: 15, color: Colors.blue),
textAlign: TextAlign.left,
),
onTap: () =>
this.setState(() => this.bytes = Uint8List(0)),
),
),
Text('|', style: TextStyle(fontSize: 15, color: Colors
.black26)),
Expanded(
flex: 5,
child: GestureDetector(
onTap: () async {
final success = await ImageGallerySaver.saveImage(
this.bytes);
SnackBar snackBar;
if (success) {
snackBar = new SnackBar(content: new Text(
'Successful Preservation!'));
Scaffold.of(context).showSnackBar(snackBar);
} else {
snackBar =
new SnackBar(content: new Text('Save failed!'));
}
},
child: Text(
'save',
style: TextStyle(
fontSize: 15, color: Colors.blue),
textAlign: TextAlign.right,
),
),
),
],
),
)
],
),
),
Divider(height: 2, color: Colors.black26),
],
),
),
);
}
Widget _buttonGroup() {
return Row(
children: <Widget>[
Expanded(
flex: 1,
child: SizedBox(
height: 120,
child: InkWell(
onTap: () => _generateBarCode(this._inputController.text),
child: Card(
child: Column(
children: <Widget>[
Expanded(
flex: 2,
child: Image.asset('images/generate_qrcode.png'),
),
Divider(height: 20),
Expanded(flex: 1, child: Text("Generate")),
],
),
),
),
),
),
Expanded(
flex: 1,
child: SizedBox(
height: 120,
child: InkWell(
onTap: _scan,
child: Card(
child: Column(
children: <Widget>[
Expanded(
flex: 2,
child: Image.asset('images/scanner.png'),
),
Divider(height: 20),
Expanded(flex: 1, child: Text("Scan")),
],
),
),
),
),
),
Expanded(
flex: 1,
child: SizedBox(
height: 120,
child: InkWell(
onTap: _scanPhoto,
child: Card(
child: Column(
children: <Widget>[
Expanded(
flex: 2,
child: Image.asset('images/albums.png'),
),
Divider(height: 20),
Expanded(flex: 1, child: Text("Scan Photo")),
],
),
),
),
),
),
],
);
}
Future _scan() async {
String barcode = await scanner.scan();
if (barcode == null) {
print('nothing return.');
} else {
this._outputController.text = barcode;
}
}
Future _scanPhoto() async {
String barcode = await scanner.scanPhoto();
this._outputController.text = barcode;
}
Future _scanPath(String path) async {
String barcode = await scanner.scanPath(path);
this._outputController.text = barcode;
}
Future _scanBytes() async {
File file = await ImagePicker.pickImage(source: ImageSource.camera);
Uint8List bytes = file.readAsBytesSync();
String barcode = await scanner.scanBytes(bytes);
this._outputController.text = barcode;
}
Future _generateBarCode(String inputCode) async {
Uint8List result = await scanner.generateBarCode(inputCode);
this.setState(() => this.bytes = result);
}
}
class MyAppState extends State<MyApp> {
Future<SharedPreferences> _sPrefs = SharedPreferences.getInstance();
final TextEditingController controller = TextEditingController();
List<String> listOne, listTwo;
#override
void initState() {
super.initState();
listOne = [];
listTwo = [];
}
Future<Null> addString() async {
final SharedPreferences prefs = await _sPrefs;
listOne.add(controller.text);
prefs.setStringList('list', listOne);
setState(() {
controller.text = '';
});
}
Future<Null> clearItems() async {
final SharedPreferences prefs = await _sPrefs;
prefs.clear();
setState(() {
listOne = [];
listTwo = [];
});
}
Future<Null> getStrings() async {
final SharedPreferences prefs = await _sPrefs;
listTwo = prefs.getStringList('list');
setState(() {});
}
Future<Null> updateStrings(String str) async {
final SharedPreferences prefs = await _sPrefs;
setState(() {
listOne.remove(str);
listTwo.remove(str);
});
prefs.setStringList('list', listOne);
}
#override
Widget build(BuildContext context) {
getStrings();
return Center(
child: ListView(
children: <Widget>[
TextField(
controller: controller,
decoration: InputDecoration(
hintText: 'Type in something...',
)),
RaisedButton(
child: Text("Submit"),
onPressed: () {
addString();
},
),
RaisedButton(
child: Text("Clear"),
onPressed: () {
clearItems();
},
),
Flex(
direction: Axis.vertical,
children: listTwo == null
? []
: listTwo
.map((String s) => Dismissible(
key: Key(s),
onDismissed: (direction) {
updateStrings(s);
},
child: ListTile(
title: Text(s),
)))
.toList(),
)
],
),
);
}
}
Here the first Appstate creates a Qr code reader. Second is for creating an input controller with shared preferences that can store and retrieve data locally. But when running the code the app displays only the qrscan part and 2nd is not working. I'm new to Flutter. I've just started working on Android Studio. Can anybody help please?
Try to call Another class from home property of the MyApp class.
As you can see in this image
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
//Here I have called MyWidget Class
home: MyWidget()
);
}
}
class MyWidget extends StatefulWidget {
#override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
Uint8List bytes = Uint8List(0);
TextEditingController _inputController;
TextEditingController _outputController;
#override
initState() {
super.initState();
this._inputController = new TextEditingController();
this._outputController = new TextEditingController();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
I am developing an app with a dropdown. Below is my code. I have removed the UI design code to isolate the dropdown section itself.
class ShoppingCartUIState extends State<ShoppingCartUI> {
final _formKey = GlobalKey<FormState>();
String _checkoutDropdownValue=null;
//**UI design Code Removed**//
_showCheckoutPopup() {
String date=DateTime.now().toString();
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0)), //this right here
child: Container(
height: MediaQuery.of(context).size.height/3,
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Container(
margin: EdgeInsets.all(10),
child: Text(
"What is Your Required Delivery Date?",
style: Theme.of(context).textTheme.subtitle,
),)
],
),
Row(
children: <Widget>[
IconButton(
icon: Icon(Icons.calendar_today),
color: Colors.green,
onPressed: () {
date = "111";
},
),
Text(date)
],
),
Row(
children: <Widget>[
Container(
margin: EdgeInsets.only(top:20, left:10),
child: Text(
"What is your Airport of delivery?",
style: Theme.of(context).textTheme.subtitle,
),)
],
),
Row(
children: <Widget>[
Container(
margin: EdgeInsets.only(top:5, left:10),
child: DropdownButton(
hint: Text(
"Please Select ",
style: TextStyle(
fontSize: 14,
),
),
items: <String>[
'Skinless Boneless, Full Loins',
'brown',
'silver'
].map((data) {
return DropdownMenuItem(
child: new Text(data,
style: Theme.of(context).textTheme.body1),
value: data,
);
}).toList(),
onChanged: (String newValue) {
setState(() {
_checkoutDropdownValue = newValue;
print(newValue);
});
},
value: _checkoutDropdownValue),
)
],
),
],
),
));
}
#override
void initState() {
// TODO: implement initState
super.initState();
}
}
The issue is when I change the dropdown item, the new value never get selected. The previously selected value is always displayed. However since i am using a print when dropdown is done, I can see the item has changed.
How can I solved this issue?
Wrap your Dialog widget with StatefulBuilder to rebuild the dialog.
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: MyPage(), //TODO: Add Scaffold
);
}
}
class MyPage extends StatefulWidget {
#override
_MyPageState createState() => _MyPageState();
}
class _MyPageState extends State<MyPage> {
String date = "";
String _checkoutDropdownValue;
_showCheckoutPopup() {
return StatefulBuilder(
builder: (context, setState){
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
), //this r// ight here
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Container(
margin: EdgeInsets.all(10),
alignment: Alignment.centerLeft,
child: Text(
"What is Your Required Delivery Date?",
style: Theme.of(context).textTheme.subtitle,
),
),
Row(
children: <Widget>[
IconButton(
icon: Icon(Icons.calendar_today),
color: Colors.green,
onPressed: () {
setState(() {
date = "111";
});
},
),
Text(date)
],
),
Container(
margin: EdgeInsets.only(top: 20, left: 10),
alignment: Alignment.centerLeft,
child: Text(
"What is your Airport of delivery?",
style: Theme.of(context).textTheme.subtitle,
),
),
Row(
children: <Widget>[
Container(
margin: EdgeInsets.only(top: 5, left: 10),
child: DropdownButton<String>(
hint: Text(
"Please Select ",
style: TextStyle(
fontSize: 14,
),
),
items: <String>[
'Skinless Boneless, Full Loins',
'brown',
'silver'
].map((data) {
return DropdownMenuItem(
child: new Text(data,
style: Theme.of(context).textTheme.body1),
value: data,
);
}).toList(),
onChanged: (String newValue) {
setState(() {
_checkoutDropdownValue = newValue;
});
},
value: _checkoutDropdownValue,
),
)
],
),
],
),
),
);
},
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RaisedButton(
child: Text("Click Here"),
onPressed: () {
showDialog(
context: context,
builder: (context) => _showCheckoutPopup(),
);
},
),
),
);
}
}
can you change your onPressed to print(_checkoutDropdownValue); instead of print(newValue); that way we can see if there is a problem with the assignment
I am not using any button in alert dialog, so in action how can we prevent the overflow the alert dialog, if am using gesture detector or inkwell to get ontap or onpress function or is there any other method to do it
_showDialog(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return UnicornAlertDialog(
title: Column(
children: <Widget>[
Container(
child: Image.asset('images/done.png'),
),
const SizedBox(height: 15.0),
Container(
child: Text(
'Verify',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
)
],
),
content: Text('You have successfully verified your mobile number',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white, fontSize: 15.0)),
gradient: LinearGradient(
colors: <Color>[
Color(0xDD4a00e0),
Color(0xFF8e2de2),
],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
actions: <Widget>[
Container(
child: new GestureDetector(
onTap:(){
Navigator.push(context,
MaterialPageRoute(builder: (context) => ThirdRoute()));
} ,
),
),
]
);
});
}
You are getting overflow error due to GestureDetector used inside actions property of the dialog. If you just want user to tap anywhere on the alertDialog, you can wrap the AlertDialog with GestureDetector. With this, when user taps anywhere on the dialog, it will navigate them to thirdRoute. Working code below:
_showDialog(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return GestureDetector(
child: AlertDialog(
title:
Column(
children: <Widget>[
Container(
child: Image.asset('images/done.png'),
),
const SizedBox(height: 15.0),
Container(
child: Text(
'Verify',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.black,
fontSize: 20.0,
),
),
)
],
),
content:
Text('You have successfully verified your mobile number',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.black, fontSize: 15.0)),
// gradient: LinearGradient(
// colors: <Color>[
// Color(0xDD4a00e0),
// Color(0xFF8e2de2),
// ],
// begin: Alignment.topCenter,
// end: Alignment.bottomCenter,
// ),
actions: <Widget>[]
),
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => NextScreen()));
}
);
});
}
Hope this answers your question.
_showDialog(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return GestureDetector(
child: UnicornAlertDialog(
title: Column(
children: <Widget>[
Container(
child: Image.asset('images/done.png'),
),
const SizedBox(height: 15.0),
Container(
child: Text(
'Verify',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
)
],
),
content: Text(
'You have successfully verified your mobile number',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white, fontSize: 15.0)),
gradient: LinearGradient(
colors: <Color>[
Color(0xDD4a00e0),
Color(0xFF8e2de2),
],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
actions: <Widget>[ ]),
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => ThirdRoute()));
},
);
});
}
Unicorn alert dialog is used for background-color decoration, and since you cannot have gradient color in normal alert dialog, I used this.
code snippet
_showDialog(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return UnicornAlertDialog(
title: GestureDetector(
onTap: () { print("on tap title");},
child: Column(
children: <Widget>[
Container(
child: Image.asset('assets/images/background.jpg'),
),
const SizedBox(height: 15.0),
Container(
child: Text(
'Verify',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
)
],
),
),
content: GestureDetector(
onTap: () { print("on tap content");},
child: Text('You have successfully verified your mobile number',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white, fontSize: 15.0)),
),
gradient: LinearGradient(
colors: <Color>[
Color(0xDD4a00e0),
Color(0xFF8e2de2),
],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
actions: <Widget>[
]
);
});
}
full code
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
class UnicornAlertDialog extends StatelessWidget {
const UnicornAlertDialog({
Key key,
#required this.gradient,
this.title,
this.titlePadding,
this.titleTextStyle,
this.content,
this.contentPadding = const EdgeInsets.fromLTRB(24.0, 20.0, 24.0, 24.0),
this.contentTextStyle,
this.actions,
this.backgroundColor,
this.elevation,
this.semanticLabel,
this.shape,
}) : assert(contentPadding != null),
super(key: key);
final Gradient gradient;
final Widget title;
final EdgeInsetsGeometry titlePadding;
final TextStyle titleTextStyle;
final Widget content;
final EdgeInsetsGeometry contentPadding;
final TextStyle contentTextStyle;
final List<Widget> actions;
final Color backgroundColor;
final double elevation;
final String semanticLabel;
final ShapeBorder shape;
#override
Widget build(BuildContext context) {
assert(debugCheckHasMaterialLocalizations(context));
final ThemeData theme = Theme.of(context);
final DialogTheme dialogTheme = DialogTheme.of(context);
final List<Widget> children = <Widget>[];
String label = semanticLabel;
if (title != null) {
children.add(Padding(
padding: titlePadding ?? EdgeInsets.fromLTRB(24.0, 24.0, 24.0, content == null ? 20.0 : 0.0),
child: DefaultTextStyle(
style: titleTextStyle ?? dialogTheme.titleTextStyle ?? theme.textTheme.title,
child: Semantics(
child: title,
namesRoute: true,
container: true,
),
),
));
} else {
switch (defaultTargetPlatform) {
case TargetPlatform.iOS:
label = semanticLabel;
break;
case TargetPlatform.android:
case TargetPlatform.fuchsia:
label = semanticLabel ?? MaterialLocalizations.of(context)?.alertDialogLabel;
}
}
if (content != null) {
children.add(Flexible(
child: Padding(
padding: contentPadding,
child: DefaultTextStyle(
style: contentTextStyle ?? dialogTheme.contentTextStyle ?? theme.textTheme.subhead,
child: content,
),
),
));
}
if (actions != null) {
children.add(ButtonTheme.bar(
child: ButtonBar(
children: actions,
),
));
}
Widget dialogChild = IntrinsicWidth(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: children,
),
);
if (label != null)
dialogChild = Semantics(
namesRoute: true,
label: label,
child: dialogChild,
);
return Dialog(
backgroundColor: backgroundColor,
gradient: gradient,
elevation: elevation,
shape: shape,
child: dialogChild,
);
}
}
class Dialog extends StatelessWidget {
const Dialog({
Key key,
this.gradient,
this.backgroundColor,
this.elevation,
this.insetAnimationDuration = const Duration(milliseconds: 100),
this.insetAnimationCurve = Curves.decelerate,
this.shape,
this.child,
}) : super(key: key);
final Color backgroundColor;
final double elevation;
final Duration insetAnimationDuration;
final Curve insetAnimationCurve;
final ShapeBorder shape;
final Widget child;
final Gradient gradient;
static const RoundedRectangleBorder _defaultDialogShape =
RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0)));
static const double _defaultElevation = 24.0;
#override
Widget build(BuildContext context) {
final DialogTheme dialogTheme = DialogTheme.of(context);
return AnimatedPadding(
padding: MediaQuery.of(context).viewInsets + const EdgeInsets.symmetric(horizontal: 40.0, vertical: 24.0),
duration: insetAnimationDuration,
curve: insetAnimationCurve,
child: MediaQuery.removeViewInsets(
removeLeft: true,
removeTop: true,
removeRight: true,
removeBottom: true,
context: context,
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(minWidth: 280.0),
child: Material(
color: backgroundColor ?? dialogTheme.backgroundColor ?? Theme.of(context).dialogBackgroundColor,
elevation: elevation ?? dialogTheme.elevation ?? _defaultElevation,
shape: shape ?? dialogTheme.shape ?? _defaultDialogShape,
type: MaterialType.card,
child: ClipRRect(
borderRadius: _defaultDialogShape.borderRadius,
child: Container(
decoration: BoxDecoration(
gradient: gradient
),
child: child,
),
),
),
),
),
),
);
}
}
_showDialog(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return UnicornAlertDialog(
title: GestureDetector(
onTap: () { print("on tap title");},
child: Column(
children: <Widget>[
Container(
child: Image.asset('assets/images/background.jpg'),
),
const SizedBox(height: 15.0),
Container(
child: Text(
'Verify',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
)
],
),
),
content: GestureDetector(
onTap: () { print("on tap content");},
child: Text('You have successfully verified your mobile number',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white, fontSize: 15.0)),
),
gradient: LinearGradient(
colors: <Color>[
Color(0xDD4a00e0),
Color(0xFF8e2de2),
],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
actions: <Widget>[
]
);
});
}
Future<void> _ackAlert(BuildContext context) {
return showDialog<void>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Not in stock'),
content: const Text('This item is no longer available'),
actions: <Widget>[
FlatButton(
child: Text('Ok'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
enum ConfirmAction { CANCEL, ACCEPT }
Future<ConfirmAction> _asyncConfirmDialog(BuildContext context) async {
return showDialog<ConfirmAction>(
context: context,
barrierDismissible: false, // user must tap button for close dialog!
builder: (BuildContext context) {
return AlertDialog(
title: Text('Reset settings?'),
content: const Text(
'This will reset your device to its default factory settings.'),
actions: <Widget>[
FlatButton(
child: const Text('CANCEL'),
onPressed: () {
Navigator.of(context).pop(ConfirmAction.CANCEL);
},
),
FlatButton(
child: const Text('ACCEPT'),
onPressed: () {
Navigator.of(context).pop(ConfirmAction.ACCEPT);
},
)
],
);
},
);
}
Future<String> _asyncInputDialog(BuildContext context) async {
String teamName = '';
return showDialog<String>(
context: context,
barrierDismissible: false, // dialog is dismissible with a tap on the barrier
builder: (BuildContext context) {
return AlertDialog(
title: Text('Enter current team'),
content: new Row(
children: <Widget>[
new Expanded(
child: new TextField(
autofocus: true,
decoration: new InputDecoration(
labelText: 'Team Name', hintText: 'eg. Juventus F.C.'),
onChanged: (value) {
teamName = value;
},
))
],
),
actions: <Widget>[
FlatButton(
child: Text('Ok'),
onPressed: () {
Navigator.of(context).pop(teamName);
},
),
],
);
},
);
}
enum Departments { Production, Research, Purchasing, Marketing, Accounting }
Future<Departments> _asyncSimpleDialog(BuildContext context) async {
return await showDialog<Departments>(
context: context,
barrierDismissible: true,
builder: (BuildContext context) {
return SimpleDialog(
title: const Text('Select Departments '),
children: <Widget>[
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, Departments.Production);
},
child: const Text('Production'),
),
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, Departments.Research);
},
child: const Text('Research'),
),
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, Departments.Purchasing);
},
child: const Text('Purchasing'),
),
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, Departments.Marketing);
},
child: const Text('Marketing'),
),
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, Departments.Accounting);
},
child: const Text('Accounting'),
)
],
);
});
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
// TODO: implement build
return new Scaffold(
appBar: AppBar(
title: Text("Dialog"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new RaisedButton(
onPressed: () {
_showDialog(context);
},
child: const Text("Unicon Dialog"),
),
new RaisedButton(
onPressed: () {
_ackAlert(context);
},
child: const Text("Ack Dialog"),
),
new RaisedButton(
onPressed: () async {
final ConfirmAction action = await _asyncConfirmDialog(context);
print("Confirm Action $action" );
},
child: const Text("Confirm Dialog"),
),
new RaisedButton(
onPressed: () async {
final Departments deptName = await _asyncSimpleDialog(context);
print("Selected Departement is $deptName");
},
child: const Text("Simple dialog"),
),
new RaisedButton(
onPressed: () async {
final String currentTeam = await _asyncInputDialog(context);
print("Current team name is $currentTeam");
},
child: const Text("Input Dialog"),
),
],
),
),
);
}
}
void main() {
runApp(new MaterialApp(home: new MyApp()));
}