I am trying to build a side menu that will open and close when the arrow icon at the bottom of the vertical app bar seen in the screenshots below is pressed. I am currently doing this by using a global bool value named isleftWidgetCollapsed which will change the width of the side menu to 0 if isleftWidgetCollapsed is set to true.
It seems to be working correctly but only when I resize the app window as seen in the screenshots below. How can I get it to work on the press of the IconButton and without having to resize the app window every time?
Section of code from buildLeftMenu.dart:
Widget buildLeft(context, HomeViewModel model) {
final _scrollbar = ScrollController();
return Material(
textStyle: TextStyle(
color: Colors.white70,
fontFamily: 'Lato',
),
child: Row(
children: [
Container(
width: (gb.isleftWidgetCollapsed==true)
? 0
: MediaQuery.of(context).size.width * .20, //21.width,
height: 100.height,
decoration: BoxDecoration(
color: MainTheme.primary[50], //Colors.blueAccent[400],
),
Section of code from the mainHomeView.dart:
body: Container(
child: Row(
children: [
VerticalAppBar(),
buildLeft(context, HomeViewModel()),
...
onPressed section from VerticalAppBar.dart:
leading: RotatedBox(
quarterTurns: 1,
child: IconButton(
icon: Icon(gb.isleftWidgetCollapsed
? Icons.arrow_right
: Icons.arrow_left),
onPressed: () {
setState(() {
gb.isleftWidgetCollapsed = !gb.isleftWidgetCollapsed;
buildLeft(context, HomeViewModel());
});
},
)),
),
);
}
}
globals.dart :
library my_prj.globals;
bool isLoggedIn = false;
bool isleftWidgetCollapsed = false;
The call to buildLeft inside onPressed is doing nothing:
onPressed: () {
setState(() {
gb.isleftWidgetCollapsed = !gb.isleftWidgetCollapsed;
buildLeft(context, HomeViewModel());
});
},
Here is a solution using hooks_riverpod package. You will find all the info about this package here: http://riverpod.dev/
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
void main() {
runApp(
ProviderScope(
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
home: HomePage(),
),
),
);
}
class HomePage extends HookWidget {
#override
Widget build(BuildContext context) {
final menuOpened = useProvider(menuOpenedProvider).state;
return Scaffold(
body: Stack(
children: [
AnimatedPositioned(
duration: Duration(milliseconds: 300),
top: 0,
right: 0,
bottom: 0,
left: menuOpened
? kVerticalBarWidth + kLeftMenuWidth
: kVerticalBarWidth,
child: Content(),
),
AnimatedPositioned(
duration: Duration(milliseconds: 300),
top: 0,
bottom: 0,
left: menuOpened
? kVerticalBarWidth
: kVerticalBarWidth - kLeftMenuWidth,
child: LeftMenu(),
),
Align(alignment: Alignment.centerLeft, child: VerticalAppBar()),
],
),
);
}
}
class VerticalAppBar extends HookWidget {
#override
Widget build(BuildContext context) {
final menuOpened = useProvider(menuOpenedProvider).state;
return Container(
width: kVerticalBarWidth,
color: kVerticalBarColor,
child: Align(
alignment: Alignment.bottomCenter,
child: IconButton(
onPressed: () =>
context.read(menuOpenedProvider).state = !menuOpened,
icon: Icon(menuOpened ? Icons.arrow_left : Icons.arrow_right)),
),
);
}
}
class LeftMenu extends HookWidget {
#override
Widget build(BuildContext context) {
return Container(
color: kLeftMenuColor,
width: 200.0,
padding: EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
...List.generate(20, (index) => Text('Menu Item $index')),
],
),
);
}
}
class Content extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
color: kContentColor,
child: Center(
child: Text('CONTENT'),
),
);
}
}
// Provider for the Menu State
final menuOpenedProvider = StateProvider((ref) => true);
// Some constants
const double kVerticalBarWidth = 48.0;
const double kLeftMenuWidth = 200.0;
const Color kVerticalBarColor = Color(0xffc19277);
const Color kLeftMenuColor = Color(0xffe1bc91);
const Color kContentColor = Color(0xff62959c);
Related
I'm quite inexperienced with flutter and have created this script.
When you tap on the red container you create a Row of buttons,
I would like when I click on a button in the Row -> the text of the blue container becomes the same as the text contained in the tapped button
Anyone know how I can do?
Thank you :)
import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
void main() => runApp(mainApp());
class mainApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return const MaterialApp(
home: Chat(),
);
}
}
class Chat extends StatefulWidget {
const Chat({Key? key}) : super(key: key);
#override
_ChatState createState() => _ChatState();
}
class _ChatState extends State<Chat> {
String text = 'Henlo i am Gabriele!';
List<Container> OutputList = [];
void tool(String text) async {
List ListText = text.split(' ');
for (var i in ListText) {
OutputList.add(
Container(
child: GestureDetector(
onTap: () {},
child: Padding(
padding: const EdgeInsets.all(4.0),
child: Container(
color: Colors.orange,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(i),
),
),
),
),
),
);
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
children: [
GestureDetector(
onTap: () {
setState(() {
tool(text);
print(OutputList);
});
},
child: Container(
width: 150.0,
height: 50.0,
color: Colors.red,
child: Center(child: Text('START ->')),
),
),
SizedBox(height: 50.0),
Row(
children: OutputList,
),
SizedBox(height: 50.0),
Container(
color: Colors.blue,
width: 200.0,
height: 50.0,
child: Text(''),
),
],
),
),
);
}
}
Yes you can add a few line of code check here i try to solve.
import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
void main() => runApp(mainApp());
class mainApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return const MaterialApp(
home: Chat(),
);
}
}
class Chat extends StatefulWidget {
const Chat({Key? key}) : super(key: key);
#override
_ChatState createState() => _ChatState();
}
class _ChatState extends State<Chat> {
String text = 'Henlo i am Gabriele!';
//step 1 create variable
String newGeneratedText = "";
List<Container> OutputList = [];
void tool(String text) async {
List ListText = text.split(' ');
for (var i in ListText) {
OutputList.add(
Container(
child: GestureDetector(
onTap: () {
//add logic here to concatinate values
setState(() {
newGeneratedText = newGeneratedText + " " + i;//added " " for one space
});
},
child: Padding(
padding: const EdgeInsets.all(4.0),
child: Container(
color: Colors.orange,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(i),
),
),
),
),
),
);
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
children: [
GestureDetector(
onTap: () {
setState(() {
tool(text);
print(OutputList);
});
},
child: Container(
width: 150.0,
height: 50.0,
color: Colors.red,
child: Center(child: Text('START ->')),
),
),
SizedBox(height: 50.0),
Wrap( // added for fixing more values and solve overflow exceptions error
children: OutputList,
),
SizedBox(height: 50.0),
Container(
color: Colors.blue,
width: 200.0,
height: 50.0,
child: Text(newGeneratedText), //final print values
),
],
),
),
);
}
}
I am looking for a way to do widget deletion in the future.
It's easiest to describe the problem through an example (and a MWE).
The user is presented with several AnimatedPositioneds containers, representing a card game.
The PositionedContainer part means that each card can be used for Gin Rummy, Bridge, or, in fact, any abstract numbers card game.
When the user clicks one card, the card slides up (using the Animated part of AnimatedContainer)
and then we'd like the card to be removed from the stack of widgets, i.e. to "disappear" (and not just hide through opacity)
import 'package:flutter/material.dart';
import 'dart:math';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Cards'),
),
body: Center(
child: Container(
alignment: Alignment.center,
child: CardGameWidget(),
decoration: BoxDecoration(
border: Border.all(
color: Colors.blueAccent,
),
),
),
),
),
);
}
}
class CardGameWidget extends StatefulWidget {
#override
CardGameWidgetState createState() => CardGameWidgetState();
}
class CardGameWidgetState extends State<CardGameWidget> {
List<Card> cards = [];
CardGameWidgetState() {
for (var i = 0; i < 5; ++i) {
this.cards.add(Card(
offset: Offset(i * 100.0, 200),
number: Random().nextInt(1 << 16))
);
}
}
Function onTap(int index) => (newOffset) {
setState(() {
cards[index].offset += Offset(0,-100);
});
};
#override
Widget build(BuildContext context) {
List<CardWidget> cardWidgets = [];
for (int i = 0; i < this.cards.length; ++i) {
cardWidgets.add(CardWidget(
onTap: onTap(i),
offset: this.cards[i].offset,
number: this.cards[i].number,
));
}
return Stack(children: cardWidgets);
}
}
class Card {
Card({this.offset, this.number});
Offset offset;
int number;
}
class CardWidget extends StatelessWidget {
CardWidget({
Key key,
this.onTap,
this.offset,
this.number,
});
final Function onTap;
final Offset offset;
final int number;
_handleTap(details) {
onTap(details.globalPosition);
}
#override
Widget build(BuildContext context) {
return AnimatedPositioned(
left: this.offset.dx,
top: this.offset.dy,
width: 100,
height: 100,
duration: Duration(seconds: 1),
child: GestureDetector(
onTapUp: _handleTap,
child: Container(
color: Colors.cyan,
padding: EdgeInsets.all(10),
margin: EdgeInsets.all(10),
child: FittedBox(
clipBehavior: Clip.antiAlias,
alignment: Alignment.centerLeft,
fit: BoxFit.contain,
child: Text(this.number.toString()),
))),
);
}
}
How do I schedule widget deletion as a future event, after the completion of an animation?
You can look into AnimiatedList:
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, brightness: Brightness.dark),
home: SimpleAnimatedList(),
);
}
}
class SimpleAnimatedList extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: SliceAnimatedList(),
);
}
}
class SliceAnimatedList extends StatefulWidget {
#override
_SliceAnimatedListState createState() => _SliceAnimatedListState();
}
class _SliceAnimatedListState extends State<SliceAnimatedList> {
final GlobalKey<AnimatedListState> listKey = GlobalKey<AnimatedListState>();
List<int> _items = [];
int counter = 0;
Widget slideIt(BuildContext context, int index, animation) {
int item = _items[index];
TextStyle textStyle = Theme.of(context).textTheme.headline4;
return SlideTransition(
position: Tween<Offset>(
begin: const Offset(-1, 0),
end: Offset(0, 0),
).animate(animation),
child: SizedBox(
height: 128.0,
child: Card(
color: Colors.primaries[item % Colors.primaries.length],
child: Center(
child: Text('Item $item', style: textStyle),
),
),
),
);
}
#override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Expanded(
child: Container(
height: double.infinity,
child: AnimatedList(
key: listKey,
initialItemCount: _items.length,
itemBuilder: (context, index, animation) {
return slideIt(context, index, animation);
},
),
),
),
Container(
decoration: BoxDecoration(color: Colors.greenAccent),
child: Row(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
FlatButton(
onPressed: () {
setState(() {
listKey.currentState.insertItem(0,
duration: const Duration(milliseconds: 500));
_items = []
..add(counter++)
..addAll(_items);
});
},
child: Text(
"Add item to first",
style: TextStyle(color: Colors.black, fontSize: 20),
),
),
FlatButton(
onPressed: () {
if (_items.length <= 1) return;
listKey.currentState.removeItem(
0, (_, animation) => slideIt(context, 0, animation),
duration: const Duration(milliseconds: 500));
setState(() {
_items.removeAt(0);
});
},
child: Text(
"Remove first item",
style: TextStyle(color: Colors.black, fontSize: 20),
),
)
],
),
),
],
);
}
}
I was trying to implement my own AppTour it works fine, but I wanted to to add a slide transition in which the previous page slides from right to left and leaves screen viewport and next screen enters screen from outside the viewport(from right to left) . As the name suggested I read about SlideTransition and it is working with a single widget, I am confused how could I chain it to my multipple pages. My page changes are done by setState and my old page is replaced with new page just by changing image and text and selectedIndex. How should I achieve slide transition of current page leaving the screen and next page entering the screen at same time. Till now what I have made is given below. It is a working example of what I am able to acheive till yet and here is the link to codepen as well https://codepen.io/nimishbansal/pen/RwrjdNN
(note:increase editor size in codepen to get look at mobile ui portrait version)
import 'dart:async';
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: AppInitialTour(),
);
}
}
const skipTourForTesting = true;
class _TourScreen {
final String text;
final String imagePath;
_TourScreen({this.text, this.imagePath});
}
/// Pages for the screens thar are displayed in app tour.
List<_TourScreen> _pages = [
_TourScreen(text: "Page 1", imagePath: 'https://www.clker.com/cliparts/G/O/f/1/7/n/number-1-hi.png'),
_TourScreen(text: "Page 2", imagePath: 'https://upload.wikimedia.org/wikipedia/commons/thumb/6/61/NYCS-bull-trans-2.svg/1024px-NYCS-bull-trans-2.svg.png'),
_TourScreen(text: "Page 3", imagePath: 'https://webstockreview.net/images/3-clipart-three-2.png')
];
/// App tour that is shown once user launches the app for the first time.
class AppInitialTour extends StatefulWidget {
#override
_AppInitialTourState createState() => _AppInitialTourState();
}
class _AppInitialTourState extends State<AppInitialTour> {
int _selectedIndex = 1;
int _totalItems = 3;
List<Image> imageWidgets = [];
#override
void initState(){
for(var page in _pages){
imageWidgets.add(Image.network(page.imagePath),);
}
super.initState();
}
#override
void didChangeDependencies() {
for(var im in imageWidgets){
precacheImage(im.image, context);
}
super.didChangeDependencies();
}
#override
Widget build(BuildContext context) {
var _screenWidth = MediaQuery.of(context).size.width;
var _screenHeight = MediaQuery.of(context).size.height;
var _buttonTextStyle = TextStyle(fontSize: 18, color: Colors.grey[600]);
var _imageWidth = 0.75 * _screenWidth;
var _imageHeight = 0.8 * _imageWidth;
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(0),
child: AppBar(
backgroundColor: Colors.transparent,
),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Stack(
children: [
Container(
width: _screenWidth,
height: 0.8 * _screenHeight,
color: Color(0xFF45d6b9),
),
Positioned(
top: 0.25 * _screenHeight,
left: 0.12 * _screenWidth,
child: Align(
alignment: Alignment.bottomCenter,
child: Container(
width: _imageWidth,
height: _imageHeight,
child: Image.network(
_pages[_selectedIndex - 1].imagePath,
width: double.infinity,
height: double.infinity,
fit: BoxFit.fill,
),
),
),
),
Text(_pages[_selectedIndex - 1].text),
],
),
// Current Index Indicator
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
for (int i = 1; i <= _totalItems; i++)
Container(
margin: EdgeInsets.all(4),
width: 12,
height: 12,
decoration: BoxDecoration(
border: Border.all(color: Colors.black),
color: i == _selectedIndex
? Color(0xFF45d6b9)
: Colors.white,
shape: BoxShape.circle),
)
],
),
SizedBox(
height: 0.04 * _screenHeight,
),
Row(
children: [
_selectedIndex < _totalItems
? FlatButton(
child: Text(
'Skip',
style: _buttonTextStyle,
),
onPressed: () {},
)
: Container(),
Spacer(),
FlatButton(
child: Text(
_selectedIndex < _totalItems ? 'Next' : 'Done',
style: _buttonTextStyle,
),
onPressed: _selectedIndex < _totalItems
? () {
setState(() {
_selectedIndex += 1;
});
}
: () => _handleOnTapDone(context),
),
],
)
],
),
);
}
void _handleOnTapDone(BuildContext context) {
print("end");
}
}
How could I achieve such a sliding effect like this
I am extremely new to flutter and I am making an app for fun. I want to add a background image to my app but I can't find how. I know that I have to put that in BuildContext context but I can't find how. This is my code:
import 'package:audioplayers/audio_cache.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
typedef void OnError(Exception exception);
void main() {
runApp(new MaterialApp(debugShowCheckedModeBanner: false,home: LocalAudio()));
}
class LocalAudio extends StatefulWidget {
#override
_LocalAudio createState() => _LocalAudio();
}
class _LocalAudio extends State<LocalAudio> {
Duration _duration = new Duration();
Duration _position = new Duration();
AudioPlayer advancedPlayer;
AudioCache audioCache;
#override
void initState() {
super.initState();
initPlayer();
}
void initPlayer() {
advancedPlayer = new AudioPlayer();
audioCache = new AudioCache(fixedPlayer: advancedPlayer);
advancedPlayer.durationHandler = (d) => setState(() {
_duration = d;
});
advancedPlayer.positionHandler = (p) => setState(() {
_position = p;
});
}
String localFilePath;
Widget _tab(List<Widget> children) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
padding: EdgeInsets.all(16.0),
child: Column(
children: children
.map((w) => Container(child: w, padding: EdgeInsets.all(6.0)))
.toList(),
),
),
],
);
}
Widget _btn(String txt, VoidCallback onPressed) {
return ButtonTheme(
minWidth: 48.0,
child: Container(
width: 150,
height: 150,
child: RaisedButton(
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(25)),
child: Text(txt),
color: Colors.greenAccent[900],
textColor: Colors.white,
onPressed: onPressed),
),
);
}
Widget LocalAudio() {
return _tab([
_btn('Play', () => audioCache.play('bruh.mp3')),
]);
}
void seekToSecond(int second) {
Duration newDuration = Duration(seconds: second);
advancedPlayer.seek(newDuration);
}
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: 1,
child: Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
elevation: 1.0,
backgroundColor: Colors.teal,
title: Center(child: Text('BRUH')),
),
body: TabBarView(
children: [LocalAudio()],
),
),
);
}
}
I would just set the body of your scaffold to be a Stack(), and then put an image in the bottom of the stack. Should look something like this.
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: 1,
child: Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
elevation: 1.0,
backgroundColor: Colors.teal,
title: Center(child: Text('BRUH')),
),
body: Stack(
children: [
Image.asset('assets/images/background.jpg'),
TabBarView(
children: [LocalAudio()],
),
]
);
),
You can use Stack and put an image to the background, then set backgroundColor: Colors.transparent, in Scaffold widget
Stack(
children: <Widget>[
Image.asset(
"<Image.Path>",
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
fit: BoxFit.cover,
),
Scaffold(
backgroundColor: Colors.transparent,
body: Container(),
),
],
);
I am currently trying to manage the navigation logic within the flutter stack I have created.
I would like to add separate page navigation to each of the list items listed:
List<String> images = [
"assets/berries-chocolates-delicious-918327.jpg",
"assets/adult-beauty-cosmetic-1029896.jpg",
"assets/aerial-shot-architecture-beach-1488515.jpg",
"assets/brush-brushes-cosmetics-212236.jpg",
];
List<String> title = [
"Cadbury",
"Biotherme",
"Trip Advisor",
"L'Oreal Paris",
];
> This is the associated stack logic code in another file:
Stack(
children: <Widget>[
CardScrollWidget(currentPage),
Positioned.fill(
child: PageView.builder(
itemCount: images.length,
controller: controller,
reverse: true,
itemBuilder: (context, index) {
return Container();
},
),
)
],
),
// SizedBox(
// height: 10.0,
// ),
This is the associated widget file code:
import 'package:flutter/material.dart';
import '../screens/introductory_screen.dart';
import 'data.dart';
import 'dart:math';
import '../constants/constants.dart';
class CardScrollWidget extends StatefulWidget {
var currentPage;
CardScrollWidget(this.currentPage);
#override
_CardScrollWidgetState createState() => _CardScrollWidgetState();
}
class _CardScrollWidgetState extends State<CardScrollWidget> {
var padding = 20.0;
var verticalInset = 20.0;
#override
Widget build(BuildContext context) {
return new AspectRatio(
aspectRatio: widgetAspectRatio,
child: LayoutBuilder(builder: (context, contraints) {
var width = contraints.maxWidth;
var height = contraints.maxHeight;
var safeWidth = width - 2 * padding;
var safeHeight = height - 2 * padding;
var heightOfPrimaryCard = safeHeight;
var widthOfPrimaryCard = heightOfPrimaryCard * cardAspectRatio;
var primaryCardLeft = safeWidth - widthOfPrimaryCard;
var horizontalInset = primaryCardLeft / 2;
List<Widget> cardList = List();
for (var i = 0; i < images.length; i++) {
var delta = i - widget.currentPage;
bool isOnRight = delta > 0;
var start = padding +
max(
primaryCardLeft -
horizontalInset * -delta * (isOnRight ? 15 : 1),
0.0);
var cardItem = Positioned.directional(
top: padding + verticalInset * max(-delta, 0.0),
bottom: padding + verticalInset * max(-delta, 0.0),
start: start,
textDirection: TextDirection.rtl,
child: ClipRRect(
borderRadius: BorderRadius.circular(16.0),
child: Container(
decoration: BoxDecoration(
color: Colors.deepPurpleAccent,
boxShadow: [
BoxShadow(
color: Colors.black12,
offset: Offset(3.0, 6.0),
blurRadius: 10.0)
]),
child: AspectRatio(
aspectRatio: cardAspectRatio,
child: Stack(
fit: StackFit.expand,
children: <Widget>[
Image.asset(
images[i],
fit: BoxFit.cover,
),
Align(
alignment: Alignment.bottomLeft,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: EdgeInsets.symmetric(
horizontal: 16.0, vertical: 8.0),
child: Container(
decoration: BoxDecoration(
color: Colors.deepPurpleAccent,
borderRadius: BorderRadius.circular(10.0),
),
child: Padding(
padding: const EdgeInsets.all(6.0),
This is where a gesture detector will be added to create a navigation link
child: Text(
title[i],
style: kCampaignLabelStyle,
),
),
),
),
This is where a gesture detector will be added to create a navigation link
// SizedBox(
// height: 10.0,
// ),
// Padding(
// padding: const EdgeInsets.only(
// left: 12.0, bottom: 12.0),
// child: Container(
// padding: EdgeInsets.symmetric(
// horizontal: 22.0, vertical: 6.0),
// decoration: BoxDecoration(
// color: Colors.deepPurpleAccent,
// borderRadius: BorderRadius.circular(20.0)),
// child: Text(
// "Read More",
// style: TextStyle(color: Colors.white),
// ),
// ),
// )
],
),
)
],
),
),
),
),
);
cardList.add(cardItem);
}
return Stack(
children: cardList,
);
}),
);
}
}
If anyone can help with the navigation logic, I would appreciate it.
create seperate files
Cadbury.dart
class Cadbury extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return CadburyState();
}
}
class CadburyState extends State<DashboardApp> {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text("Cadbury Screen"),
backgroundColor: MyColor.colorRed,
),
backgroundColor: MyColor.colorRed,
body: new Center());
}
}
Biotherme.dart
class Biotherme extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return BiothermeState();
}
}
class BiothermeState extends State<Biotherme> {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text("Biotherme Screen"),
backgroundColor: MyColor.colorRed,
),
backgroundColor: MyColor.colorRed,
body: new Center());
}
}
and make the redirections like this
// common function to create button and redirects the page which is in callback name
Widget buttonBuilder(
String buttonText, BuildContext context, Widget callbackName) {
return new RaisedButton(
child: Text(buttonText),
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => callbackName));
});
}
// home redirection screen which redirects to the cadbury and Biotherme screen
class RedirectionScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(title: Text("Home Screen")),
body: Center(
child: new Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
buttonBuilder('Cadbury Screen', context, Cadbury()),
buttonBuilder('Biotherme Screen', context, Biotherme()),
],
),
));
}
}
try this below code for Navigation, it works for me
If you want to navigate the page on the button's click event then write code
return new RaisedButton(
child: Text(buttonText),
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => redirection_page_name));
});
Note: Here redirection_page_name is the page or widget name which you want to be load on the button's click event.
The original syntax is
Navigator.push(context, MaterialPageRoute(builder: (context) => redirection_page_name));
here context is the current screen widget context which is built, and redirection_page_name is the new page/widget which is being loaded.