I have a bottom navigation bar that redirects me to this classes:
final List pages = [
Home(),
Busca(),
Pedidos(),
Perfil(),
];
But i have multiple classes in each of these pages and it only shows the one it is being redirect to.
How can i show all the classes that i have in each file?
That is my file that represents the "Busca" page:
class Busca extends StatefulWidget {
#override
_BuscaState createState() => _BuscaState();
}
class _BuscaState extends State<Busca> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: SearchBar<Post>(
searchBarStyle: SearchBarStyle(
backgroundColor: Colors.tealAccent.withOpacity(0.7),
padding: EdgeInsets.all(5),
borderRadius: BorderRadius.circular(10),),
onSearch: search,
loader: Center(
child: Text("Buscando..."),
),
cancellationText: Text("Cancelar"),
crossAxisCount: 2,
indexedScaledTileBuilder: (int index) => ScaledTile.count(
index % 3 == 0 ? 2 : 2,
1,
),
hintText: "Busque Pratos ou Restaurantes",
hintStyle: TextStyle(
color: Colors.grey,
),
textStyle: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
),
iconActiveColor: Colors.black,
mainAxisSpacing: 20,
crossAxisSpacing: 20,
onItemFound: (Post post, int index) {
return Container(
color: Colors.tealAccent,
child: ListTile(
title: Text(post.title),
isThreeLine: true,
subtitle: Text(post.description),
)
);
},
),
),
),
);
}
}
class Categorias extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
// Row 1
Row(
children: <Widget>[
Container(
color: Colors.blue, height: 40, width: 40, child: Text('1')),
Container(
color: Colors.blue, height: 40, width: 40, child: Text('2')),
Container(
color: Colors.red, height: 40, width: 40, child: Text('3')),
],
),
]
);
}
}
When i click the button that redirects me to "Busca" the class "Categorias" does not appear below it.
How can i make it appear as well by just redirecting to "Busca"?
You can copy paste run full code below
You can use Column and Expaneded flex
code snippet
Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Column(
children: [
Expanded(
flex: 1,
child: SearchBar<Post>(
...
),
Expanded(flex: 1, child: Categorias())
],
working demo
full code
import 'dart:math';
import 'package:flappy_search_bar/scaled_tile.dart';
import 'package:flappy_search_bar/search_bar_style.dart';
import 'package:flutter/material.dart';
import 'package:flappy_search_bar/flappy_search_bar.dart';
class Post {
final String title;
final String body;
final String description;
Post(this.title, this.body, this.description);
}
class Busca extends StatefulWidget {
#override
_BuscaState createState() => _BuscaState();
}
class _BuscaState extends State<Busca> {
bool isReplay = false;
Future<List<Post>> search(String text) async {
await Future.delayed(Duration(seconds: text.length == 4 ? 10 : 1));
if (isReplay) return [Post("Replaying !", "Replaying body", "desc")];
if (text.length == 5) throw Error();
if (text.length == 6) return [];
List<Post> posts = [];
var random = new Random();
for (int i = 0; i < 10; i++) {
posts.add(Post(
"$text $i", "body random number : ${random.nextInt(100)}", "desc"));
}
return posts;
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Column(
children: [
Expanded(
flex: 1,
child: SearchBar<Post>(
searchBarStyle: SearchBarStyle(
backgroundColor: Colors.tealAccent.withOpacity(0.7),
padding: EdgeInsets.all(5),
borderRadius: BorderRadius.circular(10),
),
onSearch: search,
loader: Center(
child: Text("Buscando..."),
),
//cancellationText: Text("Cancelar"),
crossAxisCount: 2,
indexedScaledTileBuilder: (int index) => ScaledTile.count(
index % 3 == 0 ? 2 : 2,
1,
),
hintText: "Busque Pratos ou Restaurantes",
hintStyle: TextStyle(
color: Colors.grey,
),
textStyle: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
),
iconActiveColor: Colors.black,
mainAxisSpacing: 20,
crossAxisSpacing: 20,
onItemFound: (Post post, int index) {
return Container(
color: Colors.tealAccent,
child: ListTile(
title: Text(post.title),
isThreeLine: true,
subtitle: Text(post.description),
));
},
),
),
Expanded(flex: 1, child: Categorias())
],
),
),
),
);
}
}
class Categorias extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
// Row 1
Row(
children: <Widget>[
Container(
color: Colors.blue, height: 40, width: 40, child: Text('1')),
Container(
color: Colors.blue, height: 40, width: 40, child: Text('2')),
Container(
color: Colors.red, height: 40, width: 40, child: Text('3')),
],
),
]);
}
}
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: Busca(),
);
}
}
call Categoria within the Buca class. How you do this will depend on which type of layout you are aiming for. What you could go is place everything you have in Buca within the children of a column, the next child within children could be categoria.
This Would effectively allow whatever you have in Categoria to be rendered right after Buca.
I don't want to confuse you since you are a beginner, all you need to do is find the right widget container that can hold multiple widgets ie. something with the children attribute. Column, ListView, GridView or Row should do Just fine.
body: Column(children:[SafeArea........
, Categorias()
]'''
Related
I am using Listview.separated and I am using google_mobile_ads as the package to integrate the ads. I followed the example here but dint get the exact what I needed.
I called the banner ad in separatorBuilder but that either gives the divider or the ad after every nth row.
I need insert the after every 4th row in the listview.separated.
ListView.separated(
scrollDirection: Axis.vertical,
shrinkWrap: true,
controller: _scrollController,
itemCount: articleslist.length + 1,
itemBuilder: (BuildContext context, int index) {
if (index == articleslist.length) {
_loading = true;
return Center(
child: Row(
children: [
Container(
padding: EdgeInsets.all(5),
child: CircularProgressIndicator(
color: Colors.deepOrange[800],
),
),
SizedBox(
width: 15,
),
Text(
'Articles are being loaded...',
style: TextStyle(color: Colors.deepOrange[800]),
)
],
),
);
} else {
Text(
'No data to load',
style: TextStyle(color: Colors.deepOrange[800]),
);
}
if (articleslist.length == 0) {
return Container(
child: Center(
child: Text('Loading...',
style: TextStyle(color: Colors.deepOrange))));
} else {
var imgUrl = articleslist[index].img.toString();
imgUrl = BaseUrl + imgUrl.toString();
var title = articleslist[index].title;
title = title.replaceAll(RegExp(r'<[^>]*>'), '');
var body = articleslist[index].body;
body = body.replaceAll(RegExp(r'<[^>]*>'), '');
return InkWell(
onTap: () {
print('Tapped : ${articleslist[index].nid}');
print(index);
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) => DetailPage(
articleslist[index].title,
articleslist[index].img,
articleslist[index].nid,
articleslist[index].uid,
articleslist[index].created,
)));
},
child: Container(
padding: EdgeInsets.fromLTRB(8.0, 6.0, 8.0, 0.0),
child: Row(
// crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Container(
width: 120,
height: 75,
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: imgUrl == 'No img'
? Image.asset('images/placeholder.png',
height: 220, fit: BoxFit.cover)
: FadeInImage.assetNetwork(
placeholder: 'images/placeholder.png',
image: imgUrl,
height: 220,
fit: BoxFit.cover,
),
),
),
const SizedBox(
width: 20,
),
Expanded(
child: Column(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
title,
style: TextStyle(
color: Colors.black, fontSize: 16),
),
const SizedBox(
height: 10,
),
Text(
'author : $uid',
style: TextStyle(
fontSize: 10,
),
),
const SizedBox(
height: 5,
),
Text(
created,
style: TextStyle(
fontSize: 10,
),
)
],
),
),
],
),
),
);
}
},
separatorBuilder: (context, index) => Divider(),
),
You can add a item nth place using ListView.separated and '%' operator.
You just change from number '4' after '%' operator to what you want to add to nth place.
...
if ((index + 1) % 4 == 0) {
...
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,
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> {
FocusNode focusNode = FocusNode();
#override
void initState() {
super.initState();
focusNode.addListener(() {
print('1: ${focusNode.hasFocus}');
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: _buildBody(),
);
}
Widget _buildBody() {
return ListView.separated(
itemCount: 20,
separatorBuilder: (context, index) {
if ((index + 1) % 4 == 0) {
return Container(
height: 100,
color: Colors.yellow,
child: Text('it is ads'),
);
} else {
return Container();
}
},
itemBuilder: (context, index) {
return Container(
height: 100,
color: Colors.blue,
child: Text('item index: $index'),
);
},
);
}
}
Is there a way to show a slider under the number stepper widget?
Depending upon the activeStep in the number stepper the slider should be placed under the activeStep.
Any suggestions?
I'm attaching an image of the desired result.
#override
Widget build(BuildContext context) {
screenWidth = MediaQuery.of(context).size.width;
questionsProgressBarWidth = screenWidth - 80.0;
return Scaffold(
backgroundColor: Colors.white,
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
SizedBox(
height: 20,
),
TutorialTestTopBar(screenWidth: screenWidth),
SizedBox(
height: 10,
),
Padding(
padding: const EdgeInsets.all(10.0),
child: quizQuestionWidget,
),
Spacer(),
],
),
),
);
}
Widget get quizQuestionWidget {
if (quizQuestion == null) {
return const Center(child: CircularProgressIndicator());
}
questions = quizQuestion.questions;
upperBound = questions.length;
for (int i = 1; i <= questions.length; i++) {
numbers.add(i);
}
return SizedBox(
height: MediaQuery.of(context).size.height * 0.85,
child: Column(
children: [
NumberStepper(
stepColor: Colors.white,
activeStepColor: Colors.green,
// activeStepBorderColor: Colors.green,
stepRadius: 15,
direction: Axis.horizontal,
lineColor: Colors.white,
numbers: numbers,
activeStep: activeStep,
onStepReached: (index) {
setState(() {
activeStep = index;
});
},
),
//NEED THE SLIDER HERE
Expanded(
child: PageView.builder(
controller: pageController,
onPageChanged: (value) {
setState(() {
pageChanged = value;
});
},
itemBuilder: (context, index) {
return buildContent(questions[index], index, upperBound);
},
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
previousButton(),
nextButton(),
],
),
],
),
);
}
You can define a custom border for each item, then update the Color property based on the current question being answered. Full example code:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
home: SomeScreen(),
);
}
}
class SomeScreen extends StatefulWidget {
#override
_SomeScreenState createState() => _SomeScreenState();
}
class _SomeScreenState extends State<SomeScreen> {
int _currentQuestion = 0;
List<int> _answered = [];
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Container(
padding: EdgeInsets.all(20),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: List<Widget>.generate(
5,
(index) => _buildItem(index),
),
),
Container(
child: FlatButton(
color: Colors.orange,
onPressed: () {
setState(() {
if (!_answered.contains(_currentQuestion))
_answered.add(_currentQuestion);
if (_currentQuestion < 5) {
_currentQuestion += 1;
}
});
},
child: Text('Answer'),
),
)
],
),
),
),
);
}
Column _buildItem(int index) {
return Column(
children: [
Container(
child: CircleAvatar(
backgroundColor:
_answered.contains(index) ? Colors.green : Colors.transparent,
child: Text(
'${index + 1}',
style: TextStyle(color: Colors.black),
)),
),
Container(
height: 10,
width: 40,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: _currentQuestion == index
? Colors.orange
: Colors.transparent),
)
],
);
}
}
Result:
try this:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
}
class MyWidget extends StatelessWidget {
List<int> _steps = [1, 2, 3, 4, 5];
#override
Widget build(BuildContext context) {
return Container(
width: MediaQuery.of(context).size.width,
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: _numberStep(),
),
SizedBox(height: 10),
Stack(children: [
Container(
margin: EdgeInsets.symmetric(horizontal: 50),
width: MediaQuery.of(context).size.width,
height: 20,
decoration: BoxDecoration(
color: Colors.grey,
borderRadius: const BorderRadius.all(Radius.circular(10.0)),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: _sliderStep(),
),
]),
],
),
);
}
List<Widget> _numberStep() {
List<Widget> _stepList = [];
_steps.forEach((step) {
_stepList.add(
Container(
alignment: Alignment.center,
width: 20,
height: 20,
decoration: BoxDecoration(
color: step < 3? Colors.green: Colors.transparent,
shape: BoxShape.circle,
),
child: Text(step.toString()),
),
);
});
return _stepList;
}
List<Widget> _sliderStep() {
List<Widget> _sliderList = [];
_steps.forEach((step) {
_sliderList.add(
Container(
width: 40,
height: 20,
decoration: BoxDecoration(
color: step == 3? Colors.orange: Colors.transparent,
borderRadius: const BorderRadius.all(Radius.circular(10.0)),
),
),
);
});
return _sliderList;
}
}
I am Writing a small quiz game, in which I am pressing the button and these buttons are going to the empty text fields, I don't know how to send the text of the button to the text fields.
here is my code :
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(home: NinjaCard()));
class NinjaCard extends StatefulWidget {
#override
_NinjaCardState createState() => _NinjaCardState();
}
class _NinjaCardState extends State<NinjaCard> {
String result = "";
String shaka = "";
var text;
String str;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(title: Text('Animals'), backgroundColor: Colors.green),
body: Padding(
padding: EdgeInsets.all(15),
child: Column(
children: <Widget>[
Center(
child: Image.asset('lib/photo-1495594059084-33752639b9c3.jpg'),
),
SizedBox(width: 10, height: 10),
Row(children: <Widget>[
Container(
color: Colors.grey,
width: 40.0,
child: Text('$result', style: TextStyle(fontSize: 10.0, height: 2.0, color: Colors.black)),
),
SizedBox(width: 10),
Container(
color: Colors.grey,
width: 40.0,
child: Text('$shaka', style: TextStyle(fontSize: 10.0, height: 2.0, color: Colors.black)),
),
SizedBox(width: 15),
Row(
children: <Widget>[
SizedBox(
width: 50,
child: RaisedButton(
onPressed: () {},
color: Colors.green,
splashColor: Colors.red,
child: Text('S', style: TextStyle(backgroundColor: Colors.green, fontSize: 20, color: Colors.white)),
),
),
SizedBox(width: 15),
SizedBox(
width: 50,
child: RaisedButton(
onPressed: () {},
color: Colors.green,
splashColor: Colors.red,
child: Text('T', style: TextStyle(backgroundColor: Colors.green, fontSize: 20, color: Colors.white)),
),
),
SizedBox(width: 15),
],
),
]),
],
),
),
);
}
}
In a simple case, I would go with a stateful widget and array of letters. Of course, it could be created and sized dynamically, below I only explain the basic idea with some simplifications (no duplicate checks, no shuffling):
import 'package:flutter/material.dart';
void main() => runApp(App());
class App extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'App',
home: GuessTheWordWidget(),
);
}
}
class GuessTheWordWidget extends StatefulWidget {
#override
_GuessTheWordWidgetState createState() => _GuessTheWordWidgetState();
}
class _GuessTheWordWidgetState extends State<GuessTheWordWidget> {
String _word = 'Goldfish';
List<String> _input = List.generate(8, (_) => '');
int _position = 0;
void _press(int rune) {
setState(() {
if (_position < _input.length) {
print('Position ${_position}, rune: ${String.fromCharCode(rune)}');
_input[_position++] = String.fromCharCode(rune);
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('App'),
),
body: Center(
child: Column(children: <Widget>[
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: _input
.map((letter) => Container(
margin: const EdgeInsets.all(15.0),
padding: const EdgeInsets.all(3.0),
decoration: BoxDecoration(
border: Border.all(color: Colors.blueAccent)),
child: Text(letter),
))
.toList())),
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: _word.runes
.map((rune) => RaisedButton(
onPressed: () => _press(rune),
child: Text(String.fromCharCode(rune),
style: TextStyle(fontSize: 20)),
))
.toList())),
])),
);
}
}
Go play with this code at DartPad: https://dartpad.dev/69bae58772305c74f1688193076ecaef!
Hi I would like to know how can I access the items of a list on a different class where the list was created.Particularly i want to access items of the restaurantList on the Restaurant Screen class.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:projectfooddelivery/Src/models/restaurant.dart';
List<Restaurant> restaurantList=[
Restaurant(image:"kfcloja.jpg",distance: "2 miles away",location:"Shoprite do magoanine",restaurantName: "KFC"),
Restaurant(image:"dominos.jpg",distance: "0.9 miles away",location:"Downtown",restaurantName: "Dominos"),
Restaurant(image:"kfclogo.png",distance: "2 miles away",location:"Shoprite do magoanine",restaurantName: "KFC"),
];//I would like to access the items on the list
class RestaurantWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
height: 350,
child: ListView.builder(
scrollDirection: Axis.vertical,
itemCount: restaurantList.length,
itemBuilder: (_, index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
decoration: BoxDecoration(
border: Border.all(
width: 1.0,
color: Colors.grey[100]
),
borderRadius: BorderRadius.circular(20)
),
child: Row(
children: <Widget>[
Container(
width: 150,
child: ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Image.asset("images/${restaurantList[index].image}",fit:BoxFit.cover ,)
)
),
Padding(
padding: const EdgeInsets.all(3.0),
child: Container(
padding: EdgeInsets.all(2),
height: 70,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text("${restaurantList[index].restaurantName}",style: TextStyle(fontWeight: FontWeight.bold),),
Row(
children: <Widget>[
Icon(Icons.star,size: 15,color:Colors.yellowAccent,),
Icon(Icons.star,size: 15,color:Colors.yellowAccent),
Icon(Icons.star,size: 15,color:Colors.yellowAccent),
Icon(Icons.star,size: 15,color:Colors.yellowAccent),
Icon(Icons.star_half,size: 15,color:Colors.yellowAccent),
],
),
Text("${restaurantList[index].location}"),
Text("${restaurantList[index].distance}"),
],
),
),
),
],
),
),
);
},
),
);
}
}
In this class
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:projectfooddelivery/Src/widgets/menu_widget.dart';
import 'package:smooth_star_rating/smooth_star_rating.dart';
class RestaurantScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
width: 400,
child: Column(
children: <Widget>[
Stack(
children: <Widget>[
Image.asset(
"images/kfcloja.jpg",
fit: BoxFit.cover,
),
Positioned(
child: IconButton(
icon: Icon(Icons.keyboard_arrow_left,size: 40,color: Colors.white,),
onPressed: (){},
),
top: 15,
)
],
),
Padding(
padding: const EdgeInsets.only(top: 14, left: 14, right: 14),
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Restaurant KFC",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
Text(
"0.2 miles away",
style: TextStyle(
fontSize: 16,
),
),
],
),
Align(
alignment: Alignment.topLeft,
child: SmoothStarRating(
allowHalfRating: false,
starCount: 5,
size: 20.0,
filledIconData: Icons.blur_off,
halfFilledIconData: Icons.blur_on,
color: Colors.yellowAccent,
borderColor: Colors.yellowAccent,
spacing: 0.0),
),
Align(
alignment: Alignment.topLeft,
child: Text("200 Main St, New york"),
),
Padding(
padding: const EdgeInsets.only(
left: 30, right: 30, top: 20, bottom: 5),
child: Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
FlatButton.icon(
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(10.0),
),
color: Theme.of(context).primaryColor,
icon: Icon(
Icons.rate_review,
color: Colors.white,
),
label: Text(
'Reviews',
style: TextStyle(color: Colors.white),
),
onPressed: () {},
),
FlatButton.icon(
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(10.0),
),
color: Theme.of(context).primaryColor,
icon: Icon(
Icons.contact_phone,
color: Colors.white,
),
label: Text(
'Contact',
style: TextStyle(color: Colors.white),
),
onPressed: () {},
)
],
),
),
),
Text(
"Menu",
textAlign: TextAlign.center,
style: TextStyle(fontSize: 20),
),
MenuWidget(),
],
)
),
)
],
),
),
);
}
}
You can send and receive the data from one screen to another as follow , you need to use the Navigator for it , In below example i am sending the data from class A to class B as follow
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => B(bean: restaurantList[index])), //// HERE B IS THE CLASS ON WHICH YOU NEED TO CARRY DATA FROM CLASS A
);
And inside the B class you need to create the contrsutor to receive the data from A like below
class B extends StatefulWidget {
Restaurant bean;
B ({Key key, #required this.bean}) : super(key: key); ////YOU WILL GET THE DATA HERE FROM THE CONSTRUCTOR , AND USE IT INSIDE THE CLASS LIKE "widget.bean"
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return _B();
}
}
And please check the example of it to pass data from one class to another
A class which send data to B class
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'B.dart';
import 'Fields.dart';
class A extends StatefulWidget {
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return _A();
}
}
class _A extends State<A> {
Widget build(BuildContext context) {
return MaterialApp(
title: 'Screen A',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primaryColor: Colors.red,
accentColor: Color(0xFFFEF9EB),
),
home: Scaffold(
appBar: new AppBar(),
body: Container(
margin: EdgeInsets.all(20.0),
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.all(10.0),
child: Text("Screen A"),
),
Expanded(
child: ListView.builder(
itemCount: fields.length,
itemBuilder: (BuildContext ctxt, int index) {
return ListTile(
title: new Text("Rating #${fields[index].rating}"),
subtitle: new Text(fields[index].title),
onTap: (){
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => B(bean: fields [index])), //// HERE B IS THE CLASS ON WHICH YOU NEED TO CARRY DATA FROM CLASS A
);
},
);
}),
)
],
),
)));
}
}
List<Fields> fields = [
new Fields(
'One',
1,
),
new Fields(
'Two',
2,
),
new Fields(
'Three',
3,
),
new Fields(
'Four',
4,
),
new Fields(
'Five',
5,
),
];
Now check B class which receive the data from A class
import 'package:flutter/material.dart';
import 'Fields.dart';
class B extends StatefulWidget{
Fields bean;
B ({Key key, #required this.bean}) : super(key: key); ////YOU WILL GET THE DATA HERE FROM THE CONSTRUCTOR , AND USE IT INSIDE THE CLASS LIKE "widget.bean"
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return _B ();
}
}
class _B extends State<B> {
#override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
title: 'Screen A',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primaryColor: Colors.red,
accentColor: Color(0xFFFEF9EB),
),
home: Scaffold(
appBar: new AppBar(),
body: Container(
margin: EdgeInsets.all(20.0),
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.all(10.0),
child: Center(
child: Text("Screen B" ,style: TextStyle(fontSize: 20.0),),
)
),
Text("Rating=>>> ${widget.bean.rating} and Title ${widget.bean.title} ")
],
),
)));
}
}
And I have used the Pojo class for the list ,please check it once
Fields.dart
class Fields {
final String title;
final int rating;
Fields(this.title, this.rating);
}
And the output of the above program as follow.
I have the following Flutter Widget. On the right side to "+", we still see a lot of free gray space. How can I set the width of the white box to use all the leftover space, without using the absolute number?
import 'package:flutter/material.dart';
class QtyWidget extends StatefulWidget {
String title;
QtyWidget({this.title});
#override
_QtyWidgetState createState() => new _QtyWidgetState();
}
class _QtyWidgetState extends State<QtyWidget> {
int _itemCount = 1;
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
color: Colors.grey[200],
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
width: 100,
padding: EdgeInsets.fromLTRB(0, 0, 10, 0),
child: Text(
'Qty',
style: TextStyle(
fontWeight: FontWeight.normal,
fontSize: 16,
color: Colors.grey[600]),
),
),
Container(
padding: EdgeInsets.fromLTRB(15, 0, 15, 0),
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(
color: Colors.amber[800],
),
borderRadius: BorderRadius.all(Radius.circular(10))
),
child: Row(
children: <Widget>[
IconButton(icon: new Icon(Icons.remove),
onPressed: () {
setState(() {
_itemCount = _itemCount - 1 ;
if (_itemCount < 0) {
_itemCount = 1;
}
});
}),
Text(_itemCount.toString()),
IconButton(icon: new Icon(Icons.add),
onPressed: ()=>setState(()=>_itemCount++))
],
),
),
]),
);
}
}
You can copy paste run full code below
You can use wrap Container with Expanded and Row use MainAxisAlignment.center and CrossAxisAlignment.center
code snippet
Expanded(
child: Container(
padding: EdgeInsets.fromLTRB(15, 0, 15, 0),
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(
color: Colors.amber[800],
),
borderRadius: BorderRadius.all(Radius.circular(10))),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
working demo
full code
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class QtyWidget extends StatefulWidget {
String title;
QtyWidget({this.title});
#override
_QtyWidgetState createState() => new _QtyWidgetState();
}
class _QtyWidgetState extends State<QtyWidget> {
int _itemCount = 1;
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
color: Colors.grey[200],
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
width: 100,
padding: EdgeInsets.fromLTRB(0, 0, 10, 0),
child: Text(
'Qty',
style: TextStyle(
fontWeight: FontWeight.normal,
fontSize: 16,
color: Colors.grey[600]),
),
),
Expanded(
child: Container(
padding: EdgeInsets.fromLTRB(15, 0, 15, 0),
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(
color: Colors.amber[800],
),
borderRadius: BorderRadius.all(Radius.circular(10))),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
IconButton(
icon: new Icon(Icons.remove),
onPressed: () {
setState(() {
_itemCount = _itemCount - 1;
if (_itemCount < 0) {
_itemCount = 1;
}
});
}),
Text(_itemCount.toString()),
IconButton(
icon: new Icon(Icons.add),
onPressed: () => setState(() => _itemCount++))
],
),
),
),
]),
);
}
}
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> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
QtyWidget(),
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}