OpenFlutter/flutter_oktoast shows on main page only? - dart

I am using this library to show custom toast in my app. I have multiple pages in my app. The problem is, toast appears on the main page even when I call showToastWidget(...) from any other pages.
Main Page
#override
Widget build(BuildContext context) {
return OKToast(
child: Scaffold(
backgroundColor: Theme.of(context).accentColor,
body: Center(
child: SizedBox(
height: 50,
width: 50,
child: Image(image: AssetImage('assets/ic_logo.png')),
),
),
),
);
}
Page 2
#override
Widget build(BuildContext context) {
return OKToast(
child: Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('Reset Password'),
),
body: Center(
child: Padding(
padding: EdgeInsets.all(20),
child: FlatButton(
onPressed: () {
showToastWidget(
Text('Hello. I am Toast!!!'),
duration: Duration(seconds: 2),
);
},
child: Text('Show'),
),
),
),
),
);
}
When I call showToastWidget(...) from this page, it appears on Main Page
EDIT 1
I get this exception when I pass context to showToastWidget()
I/flutter (24327): The following NoSuchMethodError was thrown while handling a gesture:
I/flutter (24327): The getter 'position' was called on null.
I/flutter (24327): Receiver: null
I/flutter (24327): Tried calling: position
I/flutter (24327):
I/flutter (24327): When the exception was thrown, this was the stack:
I/flutter (24327): #0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
I/flutter (24327): #1 showToastWidget (package:oktoast/src/toast.dart:210:40)

Looks like the OKToast library does not support multiple OKToast widgets in the same app. You will have to wrap your entire app in an OKToast widget, full sample:
import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';
void main() => runApp(App());
class App extends StatelessWidget {
#override
Widget build(BuildContext context) {
return OKToast(
child: MaterialApp(
home: MainPage(),
),
);
}
}
class MainPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).accentColor,
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
FlatButton(
child: Text("Show"),
onPressed: () {
showToast(
"Main Page toast",
duration: Duration(seconds: 2),
);
},
),
SizedBox(height: 12.0),
FlatButton(
child: Text("Go to next page"),
onPressed: () => _goToNextPage(context),
),
],
),
),
);
}
void _goToNextPage(BuildContext context) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SecondPage(),
),
);
}
}
class SecondPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text("Second Page"),
),
body: Center(
child: Padding(
padding: EdgeInsets.all(20),
child: FlatButton(
onPressed: () {
showToast(
"Second Page toast",
duration: Duration(seconds: 2),
);
},
child: Text('Show'),
),
),
),
);
}
}

I am the author of OKToast, I am very glad that you use this library.
This tip of Toast is based on the design of toast in android on the mobile side.
The inspiration for OKToast itself comes from toast, so it is inevitable that it has received an impact, not adapting to the individual page-level Toast.
If you need a page-level OKToast component, you might need to do this:
import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';
import 'package:simple_widget/simple_widget.dart';
class CategoryPage extends StatefulWidget {
#override
_CategoryPageState createState() => _CategoryPageState();
}
class _CategoryPageState extends State<CategoryPage> {
#override
Widget build(BuildContext context) {
return OKToast(
child: SimpleScaffold(
title: "CategoryPage",
actions: <Widget>[
Builder(
builder: (ctx) => IconButton(
icon: Icon(Icons.trip_origin),
onPressed: () {
showToast("page toast", context: ctx); // use context to show toast in the page-level OKToast.
},
),
),
],
child: Container(),
),
);
}
}

Related

In CupertinoNavigationBar how do i show a button besides back button in leading?

I tried something like this:
#override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text(widget.title),
),
child: Center(
child: Container(
child: CupertinoButton.filled(
child: const Text('Push screen'),
onPressed: () {
CupertinoNavigationBar navBar = CupertinoNavigationBar(
leading: Row(children: <Widget>[
const CupertinoNavigationBarBackButton(),
CupertinoButton(
child: const Text('Button 2'),
padding: EdgeInsets.zero,
onPressed: () {},
),
]),
);
Navigator.push(context, CupertinoPageRoute<CupertinoPageScaffold>(
builder: (_) => CupertinoPageScaffold(
navigationBar: navBar,
child: Center(child: const Text('Content')),
)
));
},
),
),
),
);
}
And when tapping the button, it fails with
I/flutter (30855): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (30855): The following NoSuchMethodError was thrown building CupertinoNavigationBarBackButton(dirty):
I/flutter (30855): The getter 'canPop' was called on null.
I/flutter (30855): Receiver: null
I/flutter (30855): Tried calling: canPop
The reason is that this code in CupertinoNavigationBarBackButton returns null
final ModalRoute<dynamic> currentRoute = ModalRoute.of(context);
I wonder why that's the case? Is it because when I push the button, context still hasn't gotten the route yet?
What's the correct way to manually add a back button?
Thanks in advance.
Here is a very simple snippet of code. I hope it helps you:
class DemoView extends StatelessWidget {
#override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
leading: GestureDetector(
onTap: () {
debugPrint('Back button tapped');
},
child: Row(
children: <Widget>[
Icon(CupertinoIcons.left_chevron),
Text(
'Back',
style: TextStyle(
color: CupertinoColors.activeBlue,
),
),
],
),
),
middle: Text('Demo'),
trailing: GestureDetector(
onTap: () {
debugPrint('add icon tapped');
},
child: Icon(
CupertinoIcons.add,
color: CupertinoColors.black,
),
),
),
child: Center(
child: Text(
'Content',
style: TextStyle(fontSize: 36.0),
),
),
);
}
}
Which is the correct way to add manually back button?
I use code like this:
#override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text(widget.title),
leading: CupertinoNavigationBarBackButton(
onPressed: () => Navigator.of(context).pop(),
),
child: _myAppBody() // return widget
),
);
}

Flutter - Calling persistent bottom sheet from another class

I have a persistent bottom sheet in Flutter which currently exists inside an icons onPressed(){} property.
I would like to move this persistent bottom sheet to a new class on its own but I can't seem to get it working. I am still new to flutter and can't work out how to build the structure for the persistent bottom bar.
I have currently tried the below but when I run my code, I get an exception that is thrown.
main.dart
#override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: Text('Test App'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.open_in_new),
onPressed: (){
ShowBottomSheet(context);
},
)
],
),
bottom_modal_sheet.dart
final GlobalKey<ScaffoldState> _scaffoldKey = new
GlobalKey<ScaffoldState>();
void ShowBottomSheet(BuildContext context) {
_scaffoldKey.currentState.showBottomSheet<Null>((BuildContext context)
{
return new Container(
width: double.infinity,
child: new Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: EdgeInsets.only(left: 24.0, top: 16.0),
child: Text('Site Location',
style: TextStyle(fontSize: 24.0, color: Color(0xFF1181A1), fontWeight: FontWeight.bold,),
),
),
Padding(
padding: EdgeInsets.only(left: 24.0, top: 16.0),
child: Text('11 Carr Road, Three Kings, Auckland 1042',
textAlign: TextAlign.left,
style: TextStyle(fontSize: 16.0, color: Color(0xFF8596AC)),
),
),
Padding(
padding: EdgeInsets.only(left: 24.0, top: 24.0, right: 24.0, bottom: 16.0),
child: RasiedGradientButton(
child: Text('Set Location', style: TextStyle(fontSize: 24.0, fontWeight: FontWeight.bold, color: Colors.white)),
gradient: LinearGradient(
colors: <Color>[Color(0xFFFCCF58), Color(0xFFFEAA00)]
),
onPressed: (){
print('button clicked');
},
)
),
],
));
});
}
I am getting the error:
I/flutter (19024): ══╡ EXCEPTION CAUGHT BY GESTURE
╞═══════════════════════════════════════════════════════════════════
I/flutter (19024): The following NoSuchMethodError was thrown while
handling a gesture:
I/flutter (19024): The method 'showBottomSheet' was called on null.
I/flutter (19024): Receiver: null
I/flutter (19024): Tried calling: showBottomSheet<Null>(Closure:
(BuildContext) => Container)
I/flutter (19024):
You just need call showBottomSheet in your screen widget that you want show the bottom sheet and return the widget of your custom bottom sheet. The snippet show how to do this. Read the source comments.
// our Screen widget class
class MyScreen extends StatefulWidget {
#override
_MyScreenScreenState createState() => _MyScreenScreenState();
}
class _MyScreenState extends State<MyScreenScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Test App'),
actions: <Widget>[
IconButton( icon: Icon(Icons.open_in_new),
onPressed: (){
_showMyBottomSheet();
},
)
],
),
);
}
void _showMyBottomSheet(){
// the context of the bottomSheet will be this widget
//the context here is where you want to showthe bottom sheet
showBottomSheet(context: context,
builder: (BuildContext context){
return MyBottomSheetLayout(); // returns your BottomSheet widget
}
);
}
}
//your bottom sheet widget class
//you can put your things here, like buttons, callbacks and layout
class MyBottomSheetLayout extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(); // return your bottomSheetLayout
}
}

Routing to a new body from a drawer isn't working

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.

How to Fix the error "The following assertion was thrown building FutureBuilder<List<Event>>(dirty, state:"

I am trying to parse JSON and convert it into list view.
I am getting the response body and it is been converted to list also but its sending null to the future builder, I am getting this error:
/flutter ( 9715): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 9715): The following assertion was thrown building FutureBuilder<List<Event>>(dirty, state:
I/flutter ( 9715): _FutureBuilderState<List<Event>>#6efa6):
I/flutter ( 9715): A build function returned null.
I/flutter ( 9715): The offending widget is: FutureBuilder<List<Event>>
I/flutter ( 9715): Build functions must never return null. To return an empty space that causes the building widget to
I/flutter ( 9715): fill available room, return "new Container()". To return an empty space that takes as little room as
I/flutter ( 9715): possible, return "new Container(width: 0.0, height: 0.0)".
I/flutter ( 9715):
I/flutter ( 9715): When the exception was thrown, this was the stack:
The code is:
import 'package:flutter/material.dart';
import 'package:event/models/readEvent.dart';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:event/models/global.dart';
import 'dart:async';
import 'dart:convert';
import 'package:isolate/isolate_runner.dart';
Map<String, dynamic> body = {
"query": {"key": "XOXOXO", "value": "YOY", "specific": ""}
};
Future<List<Event>> fetchPosts(http.Client client) async {
http.post(URL_READEVENT, body: json.encode(body)).then((response) {
print(response.body);
final parsed = json.decode(response.body);
print(response.body);
print(parsed['rs']);
List<Event> event= (parsed["rs"] as List).map<Event>((json) =>
new Event.fromJson(json)).toList();
print(event[0].name);
return event;
});
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int _count = 0;
#override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(
title: Text(
'Events',
style: TextStyle(color: Colors.black),
),
backgroundColor: Colors.white,
),
body: Container(
child: Center(
child: Column(children: <Widget>[
Row(children: <Widget>[
Container(
padding: EdgeInsets.only(right: 20.0, left: 30.0, top: 16.0),
child: Image.asset('lib/images/dscnew.png',
width: 120.0, height: 120.0, fit: BoxFit.cover),
),
Column(children: <Widget>[
Text(
"Developer Student Clubs",
style: TextStyle(fontWeight: FontWeight.w700),
),
Text(
"VIT Vellore",
textAlign: TextAlign.left,
style: TextStyle(color: Colors.grey, fontWeight:FontWeight.w500),
)
]),
]),
new FutureBuilder(
future: fetchPosts(new http.Client()),
builder: (BuildContext context, AsyncSnapshot<List<Event>> snapshot) {
if (snapshot.hasData) {
print(snapshot.hasData);
if (snapshot.data!=null) {
print(snapshot.data);
return ListViewPosts(events: snapshot.data);
} else {
return new CircularProgressIndicator();
}
}
}
),
);
}
class ListViewPosts extends StatelessWidget {
final List<Event> events;
ListViewPosts({Key key, this.events}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
height: 600,
width: 600,
child: Expanded(child:ListView.builder(
itemCount: events.length,
padding: const EdgeInsets.all(15.0),
itemBuilder: (context, position) {
return Column(
children: <Widget>[
Divider(height: 5.0),
ListTile(
title: Text(
'${events[0].name}',
style: TextStyle(
fontSize: 22.0,
color: Colors.deepOrangeAccent,
),
),
subtitle: Text(
'${events[0].status}',
style: new TextStyle(
fontSize: 18.0,
fontStyle: FontStyle.italic,
),
),
leading: Column(
children: <Widget>[
CircleAvatar(
backgroundColor: Colors.blueAccent,
radius: 35.0,
child: Text(
'User ${events[0].clubName}',
style: TextStyle(
fontSize: 22.0,
color: Colors.white,
),
),
)
],
),
onTap: () => _onTapItem(context, events[position]),
),
],
);
}),
)
);
}
void _onTapItem(BuildContext context, Event post) {
// Scaffold
// .of(context)
// .showSnackBar(new SnackBar(content: new Text(post.id.toString() + ' - ' + post.title)));
}
}
The problem is that when your FutureBuilder returns with no data (when the FutureBuilder is first loaded) you do not return a widget.
Try changing your FutureBuilder like so:
FutureBuilder(
future: fetchPosts(new http.Client()),
builder: (BuildContext context, AsyncSnapshot<List<Event>> snapshot) {
if (snapshot.hasData) {
return ListViewPosts(events: snapshot.data);
}
return CircularProgressIndicator();
},
)
#Jordan Davies answer is definitely correct but i want to add something for iOS. If you check this in both Android and iOS then you should code like following:
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart'; // This is for IOS widgets
class API extends StatefulWidget {
#override
_APIState createState() => _APIState();
}
class _APIState extends State<API> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("POST JSON"),
),
body: Theme.of(context).platform == TargetPlatform.android
? loadAndroidLayout()
: loadIOSLayout(),
);
}
}
Widget loadIOSLayout(){
return FutureBuilder(
future: fetchPosts(new http.Client()),
builder: (BuildContext context, AsyncSnapshot<List<Event>> snapshot) {
if (snapshot.hasData) {
return ListViewPosts(events: snapshot.data);
}
return CupertinoActivityIndicator(); //IOS loading Widget
}
}
Widget loadAndroidLayout(){
return FutureBuilder(
future: fetchPosts(new http.Client()),
builder: (BuildContext context, AsyncSnapshot<List<Event>> snapshot) {
if (snapshot.hasData) {
return ListViewPosts(events: snapshot.data);
}
return CircularProgressIndicator(); //Android loading Widget
}),
}
FutureBuilder has initialData: []
return FutureBuilder(
future: fetchPosts(new http.Client()),
initialData: [],
builder: (context, AsyncSnapshot<List<dynamic>> snapshot){
return ListViewPosts(events: snapshot.data);
});

How to make a full screen dialog in flutter?

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

Resources