Related
I am new to the flutter application development and got stuck in a problem.My application contains near about 5-6 screens and all the screens contains the scaffold widget like this.
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFF332F43)
);
}
Now on all the screens i have the same concept and design like this and all the screens will share same backGround color.Now i have a button in all screens i.e. Change Theme button and on the button click of that Change Theme button i want to change all the screens Scaffold widget to be changed.Now how can i achieve this ? Please help me in my problem.
Flutter has predefined way to change background color of scaffold across app.
Just change it in MaterialApp Widget inside of your main.dart (main file).
MaterialApp(
title: 'Flutter',
theme: ThemeData(
scaffoldBackgroundColor: const Color(0xFF332F43),
),
);
Color color = Colors.blue; // make it at root level
void main() {
runApp(MaterialApp(home: Page1()));
}
In your page1 class, import above file.
class Page1 extends StatefulWidget {
#override
_Page1State createState() => _Page1State();
}
class _Page1State extends State<Page1> {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: color,
appBar: AppBar(title: Text("Page 1")),
body: Center(
child: Column(
children: <Widget>[
RaisedButton(
onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (c) => Page2())),
child: Text("Go to Page 2"),
),
RaisedButton(
child: Text("Change color"),
onPressed: () => setState(() => color = Colors.red),
),
],
),
),
);
}
}
In your page2 class, import first file.
class Page2 extends StatefulWidget {
#override
_Page2State createState() => _Page2State();
}
class _Page2State extends State<Page2> {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: color,
appBar: AppBar(title: Text("Page 2")),
body: Center(
child: Column(
children: <Widget>[
RaisedButton(
onPressed: () => Navigator.pop(context),
child: Text("Back"),
),
RaisedButton(
child: Text("Change color"),
onPressed: () => setState(() => color = Colors.green),
),
],
),
),
);
}
}
I am a beginner with flutter and dart. I have been trying to implement a navigationBar on three different pages in my app. The toggling works well for an individual page but I have problems persisting the active and inactive tabs state on all the pages. It seems like when it navigates to another page, I lose the active state too the tabs. This is my code.
AppFooter.dart
import 'package:flutter/material.dart';
class AppFooter extends StatefulWidget {
#override
_AppFooterState createState() => _AppFooterState();
}
class _AppFooterState extends State<AppFooter> {
int index = 0;
#override
Widget build(BuildContext context) {
return new Theme(
data: Theme.of(context).copyWith(
// sets the background color of the `BottomNavigationBar`
canvasColor: Colors.white,
// sets the active color of the `BottomNavigationBar` if `Brightness` is light
primaryColor: Colors.green,
textTheme: Theme.of(context)
.textTheme
.copyWith(caption: new TextStyle(color: Colors.grey))),
child: new BottomNavigationBar(
type: BottomNavigationBarType.fixed,
currentIndex: index,
onTap: (int index) {
setState(() {
this.index = index;
});
switch (index){
case 0: Navigator.of(context).pushNamed('/dashboard');
break;
case 1: Navigator.of(context).pushNamed('/medical centre');
break;
case 2: Navigator.of(context).pushNamed('/history');
break;
}
},
items: [
new BottomNavigationBarItem(
backgroundColor: Colors.white,
icon: index==0?new Image.asset('assets/images/dashboard_active.png'):new Image.asset('assets/images/dashboard_inactive.png'),
title: new Text('Dashboard', style: new TextStyle(fontSize: 12.0))),
new BottomNavigationBarItem(
backgroundColor: Colors.white,
icon: index==1?new Image.asset('assets/images/medical_sevice_active.png'):new Image.asset('assets/images/medical_sevice_inactive.png'),
title: new Text('Health Services', style: new TextStyle(fontSize: 12.0))),
new BottomNavigationBarItem(
icon: InkWell(
child: Icon(
Icons.format_align_left,
// color: green,
size: 20.0,
),
),
title: new Text('History', style: new TextStyle(fontSize: 12.0))),
]),
);
}
}
If I understand your question correctly, you need the bottom navigation bar persisted on all three pages. There is a well-written article on how to achieve it. You can find the details here.
https://medium.com/coding-with-flutter/flutter-case-study-multiple-navigators-with-bottomnavigationbar-90eb6caa6dbf
https://github.com/bizz84/nested-navigation-demo-flutter
All credits go to the original author.
Use PageView and bottomNavigationBar:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
static const String _title = 'Flutter App';
#override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: App(),
);
}
}
class App extends StatefulWidget {
App({Key key}) : super(key: key);
_AppState createState() => _AppState();
}
class _AppState extends State<App> {
PageController _myPage;
var selectedPage;
#override
void initState() {
super.initState();
_myPage = PageController(initialPage: 1);
selectedPage = 1;
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: PageView(
physics: NeverScrollableScrollPhysics(),
controller: _myPage,
children: <Widget>[
Center(
child: Text("Another Page"),
),
Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("Page 1"),
RaisedButton(
onPressed: () {
_myPage.jumpToPage(0);
setState(() {
selectedPage = 0;
});
},
child: Text("Go to another page"),
)
],
)),
Center(child: Text("Page 2")),
Center(child: Text("Page 3")),
],
),
bottomNavigationBar: BottomAppBar(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
IconButton(
icon: Icon(Icons.home),
color: selectedPage == 1 ? Colors.blue : Colors.grey,
onPressed: () {
_myPage.jumpToPage(1);
setState(() {
selectedPage = 1;
});
},
),
IconButton(
icon: Icon(Icons.star),
color: selectedPage == 2 ? Colors.blue : Colors.grey,
onPressed: () {
_myPage.jumpToPage(2);
setState(() {
selectedPage = 2;
});
},
),
IconButton(
icon: Icon(
Icons.settings,
),
color: selectedPage == 3 ? Colors.blue : Colors.grey,
onPressed: () {
_myPage.jumpToPage(3);
setState(() {
selectedPage = 3;
});
},
),
],
),
));
}
}
In addition, if you want preserve the state between pages such that going to another page won't cause the previous page to lose its state, use AutomaticKeepAliveClientMixin
Also, to lazily load the pages, PageView.builder is another solution.
Hope it helps.
Another great solution is the persistent_bottom_nav_bar package provided by Bilal Shahid.
It is easy to use and offers you a bunch of features:
Highly customizable persistent bottom navigation bar.
Ability to push new screens with or without bottom navigation bar.
20 styles for the bottom navigation bar.
Includes functions for pushing screen with or without the bottom navigation bar i.e. pushNewScreen() and pushNewScreenWithRouteSettings().
Based on flutter's Cupertino(iOS) bottom navigation bar.
Can be translucent for a particular tab.
Custom styling for the navigation bar. Click here for more information.
Handles hardware/software Android back button.
Before I found this package I followed the solution from the article #Abin mentioned in his answer. But I ran into the problem, that all screens from the navbar beeing loaded on first load of the navbar which is not that perfomant. I did not mangaed to solve this, but luckily Bilal Shahid provide a good solution with his package.
All credits to him.
Just copy & past :)
main.dart:
void main() async{
runApp(MyGrillApp());
}
class MyGrillApp extends StatelessWidget {
const MyGrillApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
routes: {
'/mainlayout': (context) => MainLayout(),
'/page1': (context) => Page1(),
'/page2': (context) => Page2(),
'/page3': (context) => Page3(),
'/page4': (context) => Page4(),
},
initialRoute: '/mainlayout',
);
}
}
main_layout.dart:
class MainLayout extends StatefulWidget {
#override
_MainLayoutState createState() => _MainLayoutState();
}
class _MainLayoutState extends State<MainLayout> {
int _currentIndex = 0;
final _page1 = GlobalKey<NavigatorState>();
final _page2 = GlobalKey<NavigatorState>();
final _page3 = GlobalKey<NavigatorState>();
final _page4 = GlobalKey<NavigatorState>();
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButtonLocation: FloatingActionButtonLocation.miniCenterDocked,
floatingActionButton: Padding(
padding: const EdgeInsets.all(6.0),
child: FloatingActionButton(
backgroundColor: Colors.redAccent,
child: const Icon(Icons.add, color: Colors.white),
onPressed: () {
// ToDo...
},
),
),
body: IndexedStack(
index: _currentIndex,
children: <Widget>[
Navigator(
key: _page1,
onGenerateRoute: (route) => MaterialPageRoute(
settings: route,
builder: (context) => Page1(),
),
),
Navigator(
key: _page2,
onGenerateRoute: (route) => MaterialPageRoute(
settings: route,
builder: (context) => Page2(),
),
),
Navigator(
key: _page3,
onGenerateRoute: (route) => MaterialPageRoute(
settings: route,
builder: (context) => Page3(),
),
),
Navigator(
key: _page4,
onGenerateRoute: (route) => MaterialPageRoute(
settings: route,
builder: (context) => Page4(),
),
),
],
),
bottomNavigationBar: BottomAppBar(
shape: const CircularNotchedRectangle(),
clipBehavior: Clip.antiAlias,
child: BottomNavigationBar(
backgroundColor: Colors.white,
currentIndex: _currentIndex,
onTap: (index) {
setState(() {
_currentIndex = index;
});
},
type: BottomNavigationBarType.fixed,
selectedItemColor: Colors.redAccent,
unselectedItemColor: Colors.grey,
showSelectedLabels: false,
showUnselectedLabels: false,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
BottomNavigationBarItem(icon: Icon(Icons.date_range), label: 'Statistics'),
BottomNavigationBarItem(icon: Icon(Icons.wallet_giftcard), label: 'Wallet'),
BottomNavigationBarItem(icon: Icon(Icons.person), label: 'Profile'),
],
),
),
);
}
}
Details screen:
class ItemDetailsPage extends StatefulWidget {
const ItemDetailsPage({Key? key}) : super(key: key);
#override
_ItemDetailsPageState createState() => _ItemDetailsPageState();
}
class _ItemDetailsPageState extends State<ItemDetailsPage> with AutomaticKeepAliveClientMixin{
#override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
appBar: AppBar(
backgroundColor: themeColorPrimary,
title: Text('Item details',),
),
body : Container(child: Text('Hello from details'),));
}
#override
bool get wantKeepAlive => true;
}
A note about routing in my solution:
If you encounter trouble when you routing by:
Navigator.pushNamed(context, '/page3');
or by:
Navigator.of(context).pushNamed(Page3());
You can fix it using MaterialPageRoute:
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => Page3(),
),
);
You can use IndexedStack to persist State when you touch/change the page
Scaffold(
body: SafeArea(
top: false,
child: IndexedStack(
//Permet de garder le state des vues même quand on change de vue
index: _currentIndex,
children: _children,
),
),
bottomNavigationBar: BottomNavigationBar( items: [ ] ),
);
I highly recommend using stack. This gives you pretty much total control over how and when you would like to show bottom app bar.
Make list of all pages you want to show using your botttomAppBar. Let's say has three icons.
final List<Widget> pages=[FirstScreen(),SecondScreen(),ThirdScreen()];
In the Build Method
Scaffold(
child: Stack(
children: <Widget>[
Navigator(
key: _navigatorKey,
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute(
builder: (BuildContext context) => pages[cur_ind],
);
},
),
],
bottomNavigationBar: BottomNavigationBar(
onTap: (int index){
setState(() {
cur_ind=index;
});
},
currentIndex: cur_ind,
fixedColor: Colors.green, //let's say
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Home'),
),
BottomNavigationBarItem(
icon: Icon(Icons.mail),
title: Text('Messages'),
),
BottomNavigationBarItem(
icon: Icon(Icons.person), title: Text('Profile'))
],
),
),
),
where cur_ind is the variable used to control which page to show. And since the body is stacked, the Bottom Navigation Bar will be persistent always.
I created a small, super easy to use package that let you do that effect CustomNavigator.
And wrote a tutorial about it on Medium you can find it here.
So it goes like this
// Here's the custom scaffold widget
// It takes a normal scaffold with mandatory bottom navigation bar
// and children who are your pages
CustomScaffold(
scaffold: Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: _items,
),
),
// Children are the pages that will be shown by every click
// They should placed in order such as
// `page 0` will be presented when `item 0` in the [BottomNavigationBar] clicked.
children: <Widget>[
Page('0'),
Page('1'),
Page('2'),
],
// Called when one of the [items] is tapped.
onItemTap: (index) {},
);
The cool thing about this library that it works efficiently. It creates a nested navigator (which is very unpleasant to do) and uses it for navigation in your widget tree.
And of course you can always use the default navigator from MaterialApp
If you are looking for a solution that performs well (that doesn't build the tabs/pages unnecessarily) even using IndexedStack take a look at my answer here
For anyone looking for this in the future auto_route handle this pretty much well with very little boilerplate using AutoTabsScaffold.
Widget build(context) {
return AutoTabsScaffold(
routes: const [
BooksRouter(),
AccountRouter(),
],
bottomNavigationBuilder: (_, tabsRouter) {
return BottomNavigationBar(
currentIndex: tabsRouter.activeIndex,
onTap: tabsRouter.setActiveIndex,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.book),
label: 'Books',
),
BottomNavigationBarItem(
icon: Icon(Icons.account_box),
label: 'Account',
),
],
);
},
);
}
I am working on a beta version of an express_app plugin, which achieve the required result.
Two days ago, I implemented an addition where you can set an ExpressHome and it can be any part of your tree, in addition to setting your routes of course. When changing the routes, everything under ExpressHome will change only and the rest will stay the same (i.e. you can have a permanent bar easily.
I will publish a more-recent version this evening, and if you would like a specific demo about your use case, let me know.
i had this issue too...after days of research i came across this package
persistent_bottom_nav_bar: ^4.0.0
it quite easy to implement.
You can use a scaffold widget to contain the whole screen then put IndexedStack widget as a Body option then use at the bottom navigation option in the scaffold widget you favorite implementation of the bottom navigation bar
Scaffold(
// here is the IndexedStack as body
body: IndexedStack(
index: this._bottomNavIndex,
children: [MangaGridView(), FavoriteManga()]),
backgroundColor: Colors.black,
bottomNavigationBar: AnimatedBottomNavigationBar(
icons: [
Icons.home_outlined,
Icons.favorite_border,
Icons.settings,
],
inactiveColor: Colors.black,
activeIndex: this._bottomNavIndex,
gapLocation: GapLocation.none,
activeColor: Theme.of(context).primaryColor,
notchSmoothness: NotchSmoothness.verySmoothEdge,
leftCornerRadius: 32,
rightCornerRadius: 32,
onTap: (index) => setState(() => this._bottomNavIndex = index),
height: 70,
splashColor: Theme.of(context).primaryColor,
splashRadius: 40.0,
splashSpeedInMilliseconds: 400,
iconSize: 34,
),
);
Navigator.of(context).pushNamed(); is for Navigation with page transition. So, in this situation, the method is not match.
You can use BottomNavigationBar with Scaffold.
example code:
class AppFooter extends StatefulWidget {
#override
_AppFooterState createState() => _AppFooterState();
}
class _AppFooterState extends State<AppFooter> {
int _currentIndex = 0;
List<Widget> _pages = [
Text("page1"),
Text("page2"),
Text("page3"),
];
#override
Widget build(BuildContext context) {
return Scaffold(
body: _pages[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
currentIndex: _currentIndex,
onTap: (int index) {
setState(() {
_currentIndex = index;
});
},
items: [
new BottomNavigationBarItem(
backgroundColor: Colors.white,
icon: _currentIndex == 0
? new Image.asset('assets/images/dashboard_active.png')
: new Image.asset('assets/images/dashboard_inactive.png'),
title:
new Text('Dashboard', style: new TextStyle(fontSize: 12.0))),
new BottomNavigationBarItem(
backgroundColor: Colors.white,
icon: _currentIndex == 1
? new Image.asset('assets/images/medical_sevice_active.png')
: new Image.asset(
'assets/images/medical_sevice_inactive.png'),
title: new Text('Health Services',
style: new TextStyle(fontSize: 12.0))),
new BottomNavigationBarItem(
icon: InkWell(
child: Icon(
Icons.format_align_left,
// color: green,
size: 20.0,
),
),
title: new Text('History', style: new TextStyle(fontSize: 12.0))),
],
),
);
}
}
Just make your index variable static
like:
static int index = 0;
I want the app bar to remain at the top of the app without changing or being animated when changing tabs so I set my code up like so, this is the main.dart:
import 'package:flutter/material.dart';
import 'package:stewart_inc_app/tabs/first.dart';
import 'package:stewart_inc_app/tabs/second.dart';
import 'package:stewart_inc_app/tabs/third.dart';
void main() {
runApp(MaterialApp(
home: Home(),
));
}
class Home extends StatefulWidget {
#override
HomeState createState() => HomeState();
}
class HomeState extends State<Home> {
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: new Text(
"Hello World",
),
),
body: Navigator(
initialRoute: 'tabs/third',
onGenerateRoute: (RouteSettings settings) {
WidgetBuilder builder;
switch (settings.name) {
case 'tabs/first':
builder = (BuildContext _) => FirstTab();
break;
case 'tabs/second':
builder = (BuildContext _) => SecondTab();
break;
case 'tabs/third':
builder = (BuildContext _) => ThirdTab();
break;
default:
throw Exception('Invalid route: ${settings.name}');
}
return MaterialPageRoute(builder: builder, settings: settings);
}),
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
DrawerHeader(
child: Text(
'Select Tab',
style: TextStyle(color: Colors.white),
),
decoration: BoxDecoration(
color: Colors.black,
),
),
ListTile(
title: Text('First Tab'),
onTap: () {
Navigator.pushNamed(context, 'tabs/first');
},
),
ListTile(
title: Text('Second Tab'),
onTap: () {
Navigator.pushNamed(context, 'tabs/second');
},
),
ListTile(
title: Text('Third Tab'),
onTap: () {
Navigator.pushNamed(context, 'tabs/third');
},
),
],
),
),
);
}
}
and this is the third tab, third.dart:
import 'package:flutter/material.dart';
class ThirdTab extends StatelessWidget {
static const String routeName = "/third";
#override
Widget build(BuildContext context) {
return new Scaffold(
body: new Container(
child: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new RaisedButton(
onPressed: () {
Navigator.pushNamed(context, 'tabs/second');
},
child: new Text("Second Tab"),
),
],
),
),
),
);
}
}
When I trigger Navigator.pushNamed(context, 'tabs/second'); in third.dart it works fine and animates a page change to the second tab. However when I trigger the same code from the main.dart drawer I get the following error:
flutter: The following assertion was thrown while handling a gesture:
flutter: Could not find a generator for route "tabs/second" in the _WidgetsAppState.
If anyone could help me overcome this problem it would be greatly appreciated.
It's probably the wrong context for Navigator.pushNamed(context, 'tabs/second');
Pass a GlobalKey to MaterialApp.navigatorKey https://docs.flutter.io/flutter/material/MaterialApp/navigatorKey.html and use this key to get the context for Navigator when you call a navigation method.
Anyone here know Flutter/Dart
i have a defaultLayout which looks a little bit like this
final title = Data.appTitle;
var pages = [HomeScreen(), SearchPage(), LivePage(), AccountPage()];
String _currentRoute;
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(title),
),
body: childViewBody(), //each class that extends Default() can modify this method to change body
//...Other Layout. BotAppBar is a custom widget
bottomNavigationBar: BotAppBar(
onTap: (index) {
setState(() {
//HERE... How can I make that whenever the BotAppBarItems are selected,.. the body is updated
});
},
items: [
BotAppBarItem(iconData: Icons.home, tooltip: Data.homeTitle),
BotAppBarItem(iconData: Icons.search, tooltip: Data.searchTitle),
BotAppBarItem(iconData: Icons.near_me, tooltip: Data.liveTitle),
BotAppBarItem(iconData: Icons.account_circle, tooltip: Data.accountTitle),
],
),
);
}
//Child class will modify this area to update screen.
childViewBody() {
return Column(
children: <Widget>[
Text('Placeholder')
],
);
}
... And this should update for any class that's extended it
for example
class HomePage extends Default {//...super}
class HomePageState extends DefaultState {
#override
String get title => Data.homeTitle; //updates title in parent class
childViewBody() {
return Column{
//Build HomeScreen Body here
}
}
}
Diagram.png
so how would i modify Default class that whenever the BotAppBar is selected, the body is updated... even if the current class loaded is a child class
You can use HeroAnimations
to open a new window over your previous window as this is how SearchWindows should be displayed to the user.
Here's a tutorial to implement it.
If HeroAnimations sounds bit too much,
use Navigation
Directions:
Create two screens
Navigate to the second screen using Navigator.push
Return to the first screen using Navigator.pop
Example
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
title: 'Navigation Basics',
home: FirstScreen(),
));
}
class FirstScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('First Screen'),
),
body: Center(
child: RaisedButton(
child: Text('Launch screen'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondScreen()),
);
},
),
),
);
}
}
class SecondScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Second Screen"),
),
body: Center(
child: RaisedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('Go back!'),
),
),
);
}
}
I want to make a full screen dialog box. Dialog box background must be opaque.
Here is an example:
How to make like this in Flutter?
You can use the Navigator to push a semi-transparent ModalRoute:
import 'package:flutter/material.dart';
class TutorialOverlay extends ModalRoute<void> {
#override
Duration get transitionDuration => Duration(milliseconds: 500);
#override
bool get opaque => false;
#override
bool get barrierDismissible => false;
#override
Color get barrierColor => Colors.black.withOpacity(0.5);
#override
String get barrierLabel => null;
#override
bool get maintainState => true;
#override
Widget buildPage(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) {
// This makes sure that text and other content follows the material style
return Material(
type: MaterialType.transparency,
// make sure that the overlay content is not cut off
child: SafeArea(
child: _buildOverlayContent(context),
),
);
}
Widget _buildOverlayContent(BuildContext context) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
'This is a nice overlay',
style: TextStyle(color: Colors.white, fontSize: 30.0),
),
RaisedButton(
onPressed: () => Navigator.pop(context),
child: Text('Dismiss'),
)
],
),
);
}
#override
Widget buildTransitions(
BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
// You can add your own animations for the overlay content
return FadeTransition(
opacity: animation,
child: ScaleTransition(
scale: animation,
child: child,
),
);
}
}
// Example application:
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Playground',
home: TestPage(),
);
}
}
class TestPage extends StatelessWidget {
void _showOverlay(BuildContext context) {
Navigator.of(context).push(TutorialOverlay());
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Test')),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Center(
child: RaisedButton(
onPressed: () => _showOverlay(context),
child: Text('Show Overlay'),
),
),
),
);
}
}
Well here is my implementation which is quite straightforward.
from first screen
Navigator.of(context).push(PageRouteBuilder(
opaque: false,
pageBuilder: (BuildContext context, _, __) =>
RedeemConfirmationScreen()));
at 2nd screen
class RedeemConfirmationScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white.withOpacity(0.85), // this is the main reason of transparency at next screen. I am ignoring rest implementation but what i have achieved is you can see.
.....
);
}
}
and here are the results.
Screenshot (Flutter's native dialog)
Call this method to show the dialog in fullscreen.
showGeneralDialog(
context: context,
barrierColor: Colors.black12.withOpacity(0.6), // Background color
barrierDismissible: false,
barrierLabel: 'Dialog',
transitionDuration: Duration(milliseconds: 400),
pageBuilder: (_, __, ___) {
return Column(
children: <Widget>[
Expanded(
flex: 5,
child: SizedBox.expand(child: FlutterLogo()),
),
Expanded(
flex: 1,
child: SizedBox.expand(
child: ElevatedButton(
onPressed: () => Navigator.pop(context),
child: Text('Dismiss'),
),
),
),
],
);
},
);
Note: This answer does not discuss making the modal transparent, but is an answer is for the stated question of "How to make a full screen dialog in flutter?". Hopefully this helps other that find this question through a search like I did, that don't need a transparent modal.
Create your modal dialog class:
class SomeDialog extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: const Text('Dialog Magic'),
),
body: new Text("It's a Dialog!"),
);
}
}
In the class that needs to open the dialog, add something like this:
void openDialog() {
Navigator.of(context).push(new MaterialPageRoute<Null>(
builder: (BuildContext context) {
return new SomeDialog();
},
fullscreenDialog: true));
}
If fullscreenDialog above is true, then the app bar will have an "x" close button. If false, it will have a "<-" back arrow.
If you need to get the result of a dialog action, add a button to your dialog that returns a value when popping the navigation stack. Something like this:
onPressed: () {
Navigator
.of(context)
.pop(new MyReturnObject("some value");
}
then in your class opening the dialog, do capture the results with something like this:
void openDialog() async {
MyReturnObject results = await Navigator.of(context).push(new MaterialPageRoute<MyReturnObject>(
builder: (BuildContext context) {
return new SomeDialog();
},
fullscreenDialog: true));
}
You can use showGeneralDialog method with any widget extends from Material like Scaffold, Card, ..etc.
For example I am going to it with Scaffold like this:
showGeneralDialog(
context: context,
pageBuilder: (context, animation, secondaryAnimation) => Scaffold(
backgroundColor: Colors.black87,
body: //Put your screen design here!
),
);
And now you can set your design as a normal screen by using Scaffold.
Note: if you want to go back you can Navigator like this:
Navigator.of(context).pop(null)
Different ways to show fullscreen dialog
A. Material Dialog
showDialog<void>(
context: context,
useSafeArea: false,
builder: (BuildContext context) {
return const SomeScaffoldView();
},
);
B. Cupertino Dialog
showCupertinoDialog<void>(
context: context,
builder: (BuildContext context) {
return const SomeScaffoldView();
},
);
C. Custom Dialog
Flutter uses this under-the-hood when displaying dialogs.
Can customize transition animation with transitionBuilder, here's a random guide with example animations.
showGeneralDialog(
context: context,
pageBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) {
return const SomeScaffoldView();
},
);
Sample Scaffold View used in above snippets.
class SomeScaffoldView extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Sample Fullscreen Dialog'),
),
body: const Center(child: Text('Dialog Body')),
);
}
}
You can use AlertDialog with zero insetPadding like below:
showDialog(
barrierDismissible: false,
context: context,
builder: (BuildContext context) {
return StatefulBuilder(builder: (context, setState) {
return AlertDialog(
insetPadding: EdgeInsets.zero,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(10.0))),
content: SizedBox.expand(
child: Column(
children: <Widget>[
SingleChildScrollView(
physics: BouncingScrollPhysics(),
child: Wrap(
children: <Widget>[
Row(
children: <Widget>[
Expanded(
flex: 1,
child: Text(
"Sample type",
style: TextStyle(fontWeight: FontWeight.w700),
),
),
Expanded(flex: 1, child: Text(""))
],
),
],
)),
],
),
));
});
},
);
RFlutter Alert is super customizable and easy-to-use alert/popup dialogs for Flutter. You may create reusable alert styles or add buttons as much as you want with ease.
Alert(context: context, title: "RFLUTTER", desc: "Flutter is awesome.").show();
RFlutter
It's easy to use! :)
you can do like this if you use popular flutter library getx
getx link
void showAlertDialogg(
String body,
String? confirmButtonText,
String? cancelButtonText,
Function(bool onConfirm, bool onCancel) clickEvent,
{barrierDismissible = false}) {
Get.dialog(
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextComponent(
body,
textAlign: TextAlign.center,
fontSize: textSmallFontSize,
fontWeight: titleFontWeight,
color: Colors.white,
),
Row(
//crossAxisAlignment : CrossAxisAlignment.center,
children: [
Expanded(
flex: 1,
child: OutlineButtonComponent(
text: cancelButtonText,
borderColor: kPrimaryColor,
onPressed: () {
Get.back();
clickEvent(false, true);
},
textColor: kPrimaryColor,
padding: EdgeInsets.fromLTRB(16, 16, 8, 16),
),
),
Expanded(
flex: 1,
child: ButtonComponent(
text: confirmButtonText,
buttonColor: kPrimaryColor,
onPressed: () {
Get.back();
clickEvent(true, false);
},
textColor: Colors.white,
padding: EdgeInsets.fromLTRB(8, 16,16, 16),
),
),
],
)
],
),
barrierColor: Colors.black12.withOpacity(0.8),
useSafeArea: true
);
}
you can pas params as you want & call this method where you need it. it supports widget so you can setup the widget as you want.
Wrap your top-level widget with Navigator widget like so:
return Navigator(
pages: [
MaterialPage(
child: MainScreen(
child: widgets...
then call showDialog and because useRootNavigator is set to true in default it will use the root navigator that we added above the MainScreen