Aligning alert dialog button bar widgets - dart

I'm new to flutter, so I'm trying to create a widget that shows an alert dialog. In the content of alert dialog I got SingleChildScrollView and in, so called, button bar I have a text, checkbox and a button, which I want to align(put checkbox with text on the left side, the button on the right side), but I don't know how. Tried expanded and flexible, also tried to insert row with mainAxisAlignment set to spaceEvenly, not working, could someone please help me?
Here is the code:
class TermsAndConditionsAlertDialog extends StatefulWidget {
TermsAndConditionsAlertDialogState createState() {
return new TermsAndConditionsAlertDialogState();
}
}
class TermsAndConditionsAlertDialogState
extends State<TermsAndConditionsAlertDialog> {
static bool _isChecked = false;
//TODO get the terms and conditions message
static final String _TERMS_AND_CONDITIONS_MESSAGE =
'blablabla this is a terms and conditions message and a blablababl and a bla bla and a aaaaaaaaaaaa bla';
static final String _DIALOG_TITLE = 'Terms and Conditions';
#override
Widget build(BuildContext context) {
// TODO: implement build
return new AlertDialog(
title: new Text(_DIALOG_TITLE),
content: new SingleChildScrollView(
child: new Text(
_TERMS_AND_CONDITIONS_MESSAGE,
style: new TextStyle(fontSize: 50.0),
),
),
actions: <Widget>[
new Text('Accept'),
new Checkbox(
// title: Text('Accept'),
value: _isChecked,
onChanged: (bool newValue) {
setState(() {
_isChecked = newValue;
});
},
),
new RaisedButton(
onPressed: () {
_printDialogResult();
_closeDialog();
//TODO add a method to move on with an app
},
child: new Text(
'Start',
style: TextStyle(color: Colors.white),
)),
],
);
}
void _printDialogResult() {
//simply prints the result in console
print('You selected 1');
}
void _closeDialog() {
if (_isChecked) {
Navigator.pop(context);
}
}
}[FL][1]

You want to use the content property to place your widgets because the actions will actually be wrapped in a ButtonBar and placed on the bottom right.
So a solution may be split the content of the dialog with a Column letting the SingleChildScrollView to expand to fill the viewport and placing a Row with your desired widgets on the bottom with the mainAxisAlignment: MainAxisAlignment.spaceBetween,. Since you also want to group the Text and CheckBox, another Row will do the job to gather both next to each other.
I've edited your example so you can copy/paste and try/tweak it yourself. This will produce the result below.
class TermsAndConditionsAlertDialog extends StatefulWidget {
TermsAndConditionsAlertDialogState createState() {
return new TermsAndConditionsAlertDialogState();
}
}
class TermsAndConditionsAlertDialogState extends State<TermsAndConditionsAlertDialog> {
static bool _isChecked = false;
static final String _TERMS_AND_CONDITIONS_MESSAGE =
'blablabla this is a terms and conditions message and a blablababl and a bla bla and a aaaaaaaaaaaa bla';
static final String _DIALOG_TITLE = 'Terms and Conditions';
#override
Widget build(BuildContext context) {
return new AlertDialog(
title: new Text(_DIALOG_TITLE),
content: new Column(
children: <Widget>[
new Expanded(
child: new SingleChildScrollView(
child: new Text(
_TERMS_AND_CONDITIONS_MESSAGE,
style: new TextStyle(fontSize: 50.0),
),
),
),
new Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
new Row(
children: <Widget>[
new Text('Accept'),
new Checkbox(
value: _isChecked,
onChanged: (bool newValue) {
setState(() {
_isChecked = newValue;
});
},
),
],
),
new RaisedButton(
onPressed: () {
_printDialogResult();
_closeDialog();
},
child: new Text(
'Start',
style: TextStyle(color: Colors.white),
)),
],
),
],
),
);
}
void _printDialogResult() {
print('You selected 1');
}
void _closeDialog() {
if (_isChecked) {
Navigator.pop(context);
}
}
}

Related

setState from parent widget doesn't update value for child

I have a StatefulWidget where there is a ListView holding several childs widget.
One of the child is a GridView containing some items.
What I would want to achieve is to rebuild this GridView child when a button is pressed from the Parent widget. The button is located in the bottomNavigationBar in the Parent widget.
However, when I pressed the button, it should go to the _resetFilter() method, which works. But the setState() doesn't seem to update the GridView build() method inside Child widget.
class ParentState extends State<Parent> {
// removed for brevity
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(...),
bottomNavigationBar: BottomAppBar(
child: new Row(
children: <Widget>[
Padding(
padding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 5.0),
child: SizedBox(
onPressed: () {
_resetFilter();
},
)
),
],
),
),
body: Container(
child: Form(
key: _formKey,
child: ListView(
children: <Widget>[
Column(
children: <Widget>[
Container(
child: Column(
children: <Widget>[
Container(...), // this works
Column(...),
Container(...), // this works
Container(
child: GridView.count(
// ...
children:
List.generate(oriSkills.length, (int i) {
bool isSkillExist = false;
if (_selectedSkills.contains(rc.titleCase)) {
isSkillExist = true;
} else {
isSkillExist = false;
}
return Child( // this doesn't work
id: oriSkills[i]['id'],
name: oriSkills[i]['description'],
skillSelect: isSkillExist, // this boolean showed correct value from the above logic
onChange: onSkillChange,
);
}),
),
),
],
),
)
],
)
],
)),
),
);
}
void _resetFilter() {
setState(() {
_theValue = 0.0;
searchC.text = "";
_selectedSkills = []; // this is the variable that I'd like the GridView to recreate from.
});
}
}
I tried to print one of the field name inside Child widget, but it always showing the old value instead of the new one.
Even after presing the button, it does passing correct value to ChildState.
class ChildState extends State<Child> {
final String name;
final MyCallbackFunction onChange;
bool skillSelect;
double size = 60.0;
ChildState({this.name, this.skillSelect, this.onChange});
#override
void initState() {
super.initState();
}
#override
void dispose() {
super.dispose();
}
void setSkillLevel() {
setState(() {
if (skillSelect) {
skillSelect = false;
onChange(name, false);
} else {
skillSelect = true;
onChange(name, true);
}
});
}
Color _jobSkillSelect(bool select) {
print(select); // always print old state instead of new state
return select ? Color(MyColor.skillLvlOne) : Color(MyColor.skillDefault);
}
#override
Widget build(BuildContext context) {
return Container(
child: Column(children: <Widget>[
InkResponse(
onTap: setSkillLevel,
child: Container(
height: size,
width: size,
decoration: BoxDecoration(
image: DecorationImage(
colorFilter: ColorFilter.mode(_jobSkillSelect(skillSelect), BlendMode.color),
),
),
)),
]));
}
}
How can I update the Child widget to have the updated value from the Parent widget after reset button is pressed?
You might want to pass the values to the actual Child class. Not to its state.
The class is whats rebuilding once your parent rebuilds. So the new values will be reflected.
So your Child implementation should look something like this (don't forget to replace the onChange Type to your custom Function.
class Child extends StatefulWidget {
final String name;
final Function(void) onChange;
final bool skillSelect;
final double size;
final Function(bool) onSkillLevelChanged;
const Child({Key key, this.name, this.onChange, this.skillSelect, this.size, this.onSkillLevelChanged}) : super(key: key);
#override
_ChildState createState() => _ChildState();
}
class _ChildState extends State<Child> {
Color _jobSkillSelect(bool select) {
print(select); // always print old state instead of new state
return select ? Color(MyColor.skillLvlOne) : Color(MyColor.skillDefault);
}
#override
Widget build(BuildContext context) {
return Container(
child: Column(
children: <Widget>[
InkResponse(
onTap: () {
if (widget.onSkillLevelChanged != null) {
widget.onSkillLevelChanged(!widget.skillSelect);
}
},
child: Container(
height: widget.size,
width: widget.size,
decoration: BoxDecoration(
image: DecorationImage(
colorFilter: ColorFilter.mode(_jobSkillSelect(widget.skillSelect), BlendMode.color),
),
),
)),
],
),
);
}
}
In this case the Child ist not responsible anymore for managing its skillSelect property. It simply calls a Function on its parent. The parent then builds with a new skillSelect boolean.
So you might use this child like this:
return Child( // this doesn't work
id: oriSkills[i]['id'],
name: oriSkills[i]['description'],
skillSelect: oriSkills[i]['isSkillExist'],
onChange: onSkillChange,
onSkillLevelChanged: (newSkillLevel) {
setState(() {
oriSkills[i]['isSkillExist'] = newSkillLevel;
});
},
);

Flutter Bottomsheet Modal not rerendering

On my grid items when I click, it opens a ModalBottomSheet and listed with filter chips of strings. When you click a filter chip value, the value is updated but the widget does not re-render. The app is a StatefulWidget.
I have called the function setState.
What I expect is filterchips becomes checked and unchecked on selection.
void _showBottom(index){
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context){
return new Container(
padding: new EdgeInsets.all(27.0),
child: new Column(
children: <Widget>[
new Text('Some headline', style: new TextStyle( fontWeight: FontWeight.bold, fontSize: 22),),
getFilterChipsWidgets(index),
],
),
);
}
);
}
Widget getFilterChipsWidgets(index)
{
List<Widget> tags_list = new List<Widget>();
for(var i=0; i<list[index]["tags"].length; i++) {
var _isSelected = true;
FilterChip item = new FilterChip(
label: Text("Filtertext",),
selected: _isSelected,
onSelected: (bool newValue) {
setState(() {
_isSelected = !_isSelected;
debugPrint(_isSelected.toString());
});
},
);
tags_list.add(item);
}
return new Row(children: tags_list);
}
You need to add height for the root node of the bottom sheet. So change your container to have a fixed height.
Container(
height: 300.0, // Add height
padding: new EdgeInsets.all(27.0),
child: new Column(
children: <Widget>[
new Text('Some headline',
style: new TextStyle(fontWeight: FontWeight.bold, fontSize: 22),),
getFilterChipsWidgets(index),
],
),
I usually calculate this dynamically based on the widgets I'm passing in. But this should get you started.
Edit
The comment I gave below was the actual answer.
You should wrap all the widgets in the bottom sheet into it's own stateful widget and set your values in there.
Modal Bottom sheet seems to call the constructor whenever any change in the UI occurs in the child widget for example changing focus inside a form.
So you need to create instances of the objects you are working with inside a parent StatefulWidget and then to reflect changes in the UI of the Model Bottom Sheet you need to call setState whenever you make changes to the data.
You need to wrap the under StatefulBuilder like this
import 'package:flutter/material.dart';
void _showBottom(index){
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context){
return StatefulBuilder( builder: (BuildContext context, StateSetter setState){
return new Container(
padding: new EdgeInsets.all(27.0),
child: new Column(
children: <Widget>[
new Text('Some headline', style: new TextStyle( fontWeight: FontWeight.bold, fontSize: 22),),
getFilterChipsWidgets(index, setState),
],
),
);
});
}
);}
Widget getFilterChipsWidgets(index, StateSetter setState)
{
List<Widget> tags_list = new List<Widget>();
for(var i=0; i<list[index]["tags"].length; i++) {
var _isSelected = true;
FilterChip item = new FilterChip(
label: Text("Filtertext",),
selected: _isSelected,
onSelected: (bool newValue) {
setState(() {
_isSelected = !_isSelected;
debugPrint(_isSelected.toString());
});
},
);
tags_list.add(item);
}
return new Row(children: tags_list);
}

flutter to enable and disable various Check_List_Tile using one boolean variable

I am new to flutter. in my project, there is a various check_list_tile depending upon the length of the List (attendance list). And I have used one Boolean variable. Now when I press on one checkbox it automatically checks all other checkboxes. Please help me in this (on tap one checkbox should not change the state of all other checkboxes except clicked). I have copied all code please check check_box_list field.
import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
import 'dart:async';
Map map_student_data;
Iterable iter_student_data,iter_student_key;
List list_student_data,list_student_key;
bool t=true,checkbox=false;
List list;
String validation="yes";
int i;
int year;
final FirebaseDatabase database = FirebaseDatabase.instance;
class IImca_attendence extends StatefulWidget {
#override
_IImca_attendenceState createState() => _IImca_attendenceState();
}
class _IImca_attendenceState extends State<IImca_attendence> {
#override
void initState(){
this.check_year();
super.initState();
}
DateTime date = DateTime.now();
Future check_year()async{
var k= await database.reference().child("NITTE/CLASS/MCA").once().then((DataSnapshot snapshot){
Map sea= snapshot.value;
Iterable iter=sea.keys;
list=iter.toList();
list.sublist(list.length-1);
list.sort();
setState(() {
year=list.length-2;
});
check();
});
}
Future check()async{
var m=await database.reference().child("NITTE/CLASS/MCA/${list[year].toString().toUpperCase()}/STUDENT").once().then((DataSnapshot currentyear){
map_student_data=currentyear.value;
iter_student_data=map_student_data.values;
iter_student_key=map_student_data.keys;
list_student_data=iter_student_data.toList();
list_student_key=iter_student_key.toList();
for(i=0;i<=list_student_data.length;i++){
bool ss=true;
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("II-MCA"),
centerTitle: true,
actions: <Widget>[
IconButton(icon: Icon(Icons.refresh),onPressed: (){
setState(() {
check_year();
});
})
],
),
body:
validation=="1"?
new Center(
child: Text("STUDENT DOSE NOT EXIST IN $year",style: TextStyle(color: Colors.grey,fontWeight: FontWeight.bold,fontSize: 20),),
):
new ListView.builder(
itemCount: list_student_data==null?0
:list_student_data.length,
itemBuilder: (BuildContext context,int index){
var student_detail= ['NAME : ${list_student_data[index]['NAME']}','GENDER : ${list_student_data[index]['CURRENT CLASS']}','PHOTO : ${list_student_data[index]['PHOTO']}'];
return new Container(
child: new Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
new Card(
child: new Container(
child: CheckboxListTile(
title: Text("${list_student_key[index]}",style:TextStyle(fontWeight: FontWeight.bold,),),
subtitle: Text("NAME : ${list_student_data[index]['NAME']}"),
value: checkbox,
onChanged: (val){
setState(() {
checkbox=val;
if(checkbox==true){
print("${list_student_data[index]['NAME']}: i am absent");
}if(checkbox==false){
print("${list_student_data[index]['NAME']}: i am present");
}
});
},
),
padding: EdgeInsets.all(5),
),
)
],
),
),
);
}
)
);
}
}
Well... you are using a global checkbox variable, so It's quite normal that if you change it, all widget depending on its state will change accordingly.
What I suggest you to do is to add the selected state inside your model class. Just as an example, assumed you have this Student class (I know you are using firebase, but for sake of time I don't)
class Student {
var name = 'foo';
var year = '2018';
var selected = false;
Student(this.name);
}
This class has is selected state inside of it.
Now assume that your snapshot give you 3 students. Always for sake of time I've embedded a local array:
class _IImca_attendenceState extends State<IImca_attendence> {
var _students = [Student('foo'), Student('pub'), Student('beer')];
...
(Ellipses are not part of code... ;-])
I suggest you to put your state variables inside the Stateful Widget scope and not onto the Global Scope.
That said you could have:
ListView.builder(
itemCount: _students.length,
itemBuilder: (BuildContext context, int index) {
return new Container(
child: new Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
new Card(
child: new Container(
child: CheckboxListTile(
title: Text(
_students[index].name,
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
subtitle:
Text("NAME : ${_students[index].name}"),
value: _students[index].selected,
onChanged: (val) {
setState(() {
_students[index].selected = val;
if (!_students[index].selected) {
print(
'${_students[index].name}: i am absent');
}
if (_students[index].selected) {
print(
'${_students[index].name}: i am present');
}
});
},
),
padding: EdgeInsets.all(5),
),
)
],
),
),
);
}
)
You should also use an array of bool(s) of the same length of your snapshot data students array... but I'd like to suggest to track this information directly on your Student model.
UPDATE
As you are more comfortable using array I've change my code using a complementary array of bool of the same size of your student list.
All you have to do is an array (not a single value) of boolean values, the same size of your student array, lets call this list_student_present (I instead use list_student_present2)
At the beginning you initialize this in your check function a way like that:
list_student_data = iter_student_data.toList();
// This is the array you wanna use (first all false)
list_student_present = iter_student_data.map((_) => false).toList();
And then you will use this array of bool to check the state of your checkboxes:
itemBuilder: (BuildContext context, int index) {
return new Container(
child: new Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
new Card(
child: new Container(
child: CheckboxListTile(
title: Text(
_students[index].name,
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
subtitle:
Text("NAME : ${_students[index].name}"),
value: list_student_present[index],
onChanged: (val) {
setState(() {
list_student_present[index] = val;
if (!list_student_present[index]) {
print(
'${_students[index].name}: i am absent');
}
if (list_student_present[index]) {
print(
'${_students[index].name}: i am present');
}
});
},
),
padding: EdgeInsets.all(5),
),
)
],
),
),
);
}
Do not use my Student class (I continue using it so that I'm able to show you data without firebase), continue using your students array list from your firebase snapshot.
Full code:
import 'package:flutter/material.dart';
import 'dart:async';
Map map_student_data;
Iterable iter_student_data, iter_student_key;
List list_student_data, list_student_key, list_student_present, list_student_present2;
bool t = true;
List list;
String validation = "yes";
int i;
int year;
class Student {
var name = 'foo';
var year = '2018';
var selected = false;
Student(this.name);
}
class IImca_attendence extends StatefulWidget {
#override
_IImca_attendenceState createState() => _IImca_attendenceState();
}
class _IImca_attendenceState extends State<IImca_attendence> {
var _students = [Student('foo'), Student('pub'), Student('beer')];
#override
void initState() {
this.check_year();
super.initState();
}
DateTime date = DateTime.now();
Future check_year() async {
Map sea = {1: 'atlantic', 2: 'pacific'};
Iterable iter = sea.keys;
list = iter.toList();
list.sublist(list.length - 1);
list.sort();
setState(() {
year = list.length - 2;
});
check();
}
Future check() async {
map_student_data = {
0: {'NAME': 'foo', 'CURRENT CLASS': 'pub', 'PHOTO': ''}
};
iter_student_data = map_student_data.values;
iter_student_key = map_student_data.keys;
list_student_data = iter_student_data.toList();
// This is the array you wanna use
list_student_present = iter_student_data.map((_) => false).toList();
// This is the array for my example
list_student_present2 = _students.map((_) => false).toList();
list_student_key = iter_student_key.toList();
for (i = 0; i <= list_student_data.length; i++) {
bool ss = true;
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("II-MCA"),
centerTitle: true,
actions: <Widget>[
IconButton(
icon: Icon(Icons.refresh),
onPressed: () {
setState(() {
check_year();
});
})
],
),
body: validation == "1"
? new Center(
child: Text(
"STUDENT DOSE NOT EXIST IN $year",
style: TextStyle(
color: Colors.grey,
fontWeight: FontWeight.bold,
fontSize: 20),
),
)
: ListView.builder(
itemCount: _students.length,
itemBuilder: (BuildContext context, int index) {
return new Container(
child: new Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
new Card(
child: new Container(
child: CheckboxListTile(
title: Text(
_students[index].name,
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
subtitle:
Text("NAME : ${_students[index].name}"),
value: list_student_present2[index],
onChanged: (val) {
setState(() {
list_student_present2[index] = val;
if (!list_student_present2[index]) {
print(
'${_students[index].name}: i am absent');
}
if (list_student_present2[index]) {
print(
'${_students[index].name}: i am present');
}
});
},
),
padding: EdgeInsets.all(5),
),
)
],
),
),
);
}));
}
}
I really don't like this solution. What I suggest you is to create your PODOs (Plain Old Dart Object) representing your firebase models and deserialise them from your firebase snapshots.

State management in flutter

I've created a flutter app where I'm managing array for todolist in app. I've can add the text by add button.
I've created a widget to show in list.
My question is how am i supposed manage the UI of individual.
Code:
import 'package:flutter/material.dart';
class TodoList extends StatefulWidget {
_TodoListState createState() => new _TodoListState();
}
class _TodoListState extends State<TodoList> {
List _list = new List();
Widget listTile({String data: '[Empty data]'}) {
bool _writable = false;
TextEditingController _textController = new TextEditingController(text: data);
String _text = _textController.text;
if(!_writable){
return new Row(
children: <Widget>[
new Expanded(
child: new Text(data)
),
new IconButton(icon: new Icon(Icons.edit),
onPressed: () {
// setState(() {
_writable = ! _writable;
print(_writable.toString());
// });
}),
new IconButton(icon: new Icon(Icons.remove_circle), onPressed: null),
],
);
} else {
return new Row(
children: <Widget>[
new Expanded(
child: new TextField( controller: _textController )
),
new IconButton(icon: new Icon(Icons.done), onPressed: null),
],
);
}
}
void addInList(String string) {
print(string);
setState(() {
_list.add(string);
});
print(_list);
}
void removeFromList(int index){
}
static final TextEditingController _textController = new TextEditingController();
String get _text => _textController.text;
#override
Widget build(BuildContext context) {
Widget adderTile = new Row(
children: <Widget>[
new Expanded(
child:
new TextField(
textAlign: TextAlign.center,
controller: _textController ,
decoration: new InputDecoration( hintText: 'New item.!' ),
),
),
new IconButton(icon: new Icon(Icons.add), onPressed: (){addInList(_text);}),
],
);
return new MaterialApp(
title: 'TodoList',
home: new Scaffold(
appBar: new AppBar(title: new Text('TodoList'),),
body: new Column(
children: <Widget>[
adderTile,
new ListView.builder(
shrinkWrap: true,
itemCount: _list.length,
itemBuilder: (context, int index){
return listTile(data: _list[index]);
}
),
],
),
),
);
}
}
if i change _writable inside setState then it rerenders widget and _writable becomes false again. if i do it without setState, then _writable becomes true but widget doesn't rerender.
P.S.: i don't want to add another array in to manage which is writable and which is not. Thanks in advance.
The variable
bool _writable = false;
is declared as local variable in the method listTile(), but should be moved next to List _list = new List(); to become a member variable. Then use setState() to set it and rebuild the view.
Edit:
You should create a dedicated StatefulWidget (TodoListEntry), having _writable as member as suggested above. Move almost the whole method body of listTile(...) to the build()-method of the TodoListEntryState, make the parameter String data also a member and pass the value via the constructor.

Destruct and Construct cards in Flutter dynamically

I'm new to Flutter,
I want to destruct cards created initially and construct them again as per data provided in API call.
Basically when I tap on button in UI, it should call APIs and based on data from API call, if it is different from the data I already have, I want to destruct cards and construct them again.
How I can achieve this?
The cards will auto update their content when you make the call again, it is like refreshing your data.
I have made a simple example with a single card that shows data from this JSON Where I am calling the API first time in initState and then repeating the call each time I press on the FAB.
I am adding the index variable just to show you the updates (updating my single card with the next item in the list)
Also it is worth noting that I am handling the null or empty values poorly for the sake of time.
Also forget about the UI overflow ¯_(ツ)_/¯
class CardListExample extends StatefulWidget {
#override
_CardListExampleState createState() => new _CardListExampleState();
}
class _CardListExampleState extends State<CardListExample> {
Map cardList = {};
int index = 0;
#override
void initState() {
_getRequests();
super.initState();
}
_getRequests() async {
String url = "https://jsonplaceholder.typicode.com/users";
var httpClinet = createHttpClient();
var response = await httpClinet.get(
url,
);
var data = JSON.decode(response.body);
//print (data);
setState(() {
this.cardList = data[index];
this.index++;
});
print(cardList);
print(cardList["name"]);
}
#override
Widget build(BuildContext context) {
return new Scaffold(
floatingActionButton:
new FloatingActionButton(onPressed: () => _getRequests()),
appBar: new AppBar(
title: new Text("Card List Example"),
),
body: this.cardList != {}
? new ListView(children: <Widget>[
new Card(
child: new Column(
children: <Widget>[
new Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
new Text(
cardList["name"] ?? '',
style: Theme.of(context).textTheme.display1,
),
new Text(
this.cardList['email'] ?? '',
maxLines: 50,
),
],
),
new Text(cardList["website"] ?? '')
],
),
),
])
: new Center(child: new CircularProgressIndicator()),
);
}
}
Yes, Answer from Aziza works.
Though I used the code as below :
void main() =>
runApp(new MaterialApp(
onGenerateRoute: (RouteSettings settings) {
switch (settings.name) {
case '/about':
return new FromRightToLeft(
builder: (_) => new _aboutPage.About(),
settings: settings,
);
}
},
home : new HomePage(),
theme: new ThemeData(
fontFamily: 'Poppins',
primarySwatch: Colors.blue,
),
));
class HomePage extends StatefulWidget{
#override
HomePageState createState() => new HomePageState();
}
class HomePageState extends State<HomePage>{
List data;
Future<String> getData() async{
var response = await http.get(
Uri.encodeFull(<SOMEURL>),
headers: {
"Accept" : "application/json"
}
);
this.setState((){
data = JSON.decode(response.body);
});
return "Success";
}
#override
void initState() {
// TODO: implement initState
super.initState();
this.getData();
}
#override
Widget build(BuildContext context){
return new Scaffold(
appBar : new AppBar(
title : new Text("ABC API"),
actions: <Widget>[
new IconButton( // action button
icon: new Icon(Icons.cached),
onPressed: () => getData(),
)],
),
drawer: new Drawer(
child: new ListView(
children: <Widget> [
new Container(
height: 120.0,
child: new DrawerHeader(
padding: new EdgeInsets.all(0.0),
decoration: new BoxDecoration(
color: new Color(0xFFECEFF1),
),
child: new Center(
child: new FlutterLogo(
colors: Colors.blueGrey,
size: 54.0,
),
),
),
),
new ListTile(
leading: new Icon(Icons.chat),
title: new Text('Support'),
onTap: () {
Navigator.pop(context);
Navigator.of(context).pushNamed('/support');
}
),
new ListTile(
leading: new Icon(Icons.info),
title: new Text('About'),
onTap: () {
Navigator.pop(context);
Navigator.of(context).pushNamed('/about');
}
),
new Divider(),
new ListTile(
leading: new Icon(Icons.exit_to_app),
title: new Text('Sign Out'),
onTap: () {
Navigator.pop(context);
}
),
],
)
),
body: this.data != null ?
new ListView.builder(
itemCount: data.length,
itemBuilder: (BuildContext context, int index){
return new Container(
padding: new EdgeInsets.fromLTRB(8.0,5.0,8.0,0.0),
child: new Card(
child: new Padding(
padding: new EdgeInsets.fromLTRB(10.0,12.0,8.0,0.0),
child: new Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new ListTile(
enabled: data[index]['active'] == '1' ? true : false,
title: new Text(data[index]['header'],
style:Theme.of(context).textTheme.headline,
),
subtitle: new Text("\n" + data[index]['description']),
),
new ButtonTheme.bar(
child: new ButtonBar(
children: <Widget>[
new FlatButton(
child: new Text(data[index]['action1']),
onPressed: data[index]['active'] == '1' ? _launchURL :null,
),
],
),
),
],
),
),
),
);
},
)
:new Center(child: new CircularProgressIndicator()),
);
}
}
_launchURL() async {
const url = 'http://archive.org';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
class FromRightToLeft<T> extends MaterialPageRoute<T> {
FromRightToLeft({ WidgetBuilder builder, RouteSettings settings })
: super(builder: builder, settings: settings);
#override
Widget buildTransitions(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child) {
if (settings.isInitialRoute)
return child;
return new SlideTransition(
child: new Container(
decoration: new BoxDecoration(
boxShadow: [
new BoxShadow(
color: Colors.black26,
blurRadius: 25.0,
)
]
),
child: child,
),
position: new Tween(
begin: const Offset(1.0, 0.0),
end: const Offset(0.0, 0.0),
)
.animate(
new CurvedAnimation(
parent: animation,
curve: Curves.fastOutSlowIn,
)
),
);
}
#override Duration get transitionDuration => const Duration(milliseconds: 400);
}
The above code includes Navigation drawer, page navigation animation and also answer to the above question.

Resources