Flutter - custom alert dialog not showing - flutter
I am building a custom alert dialog using flutter/Dart and a Custom Show Dialog class that I got from Github and for a reason or another the dialog is not showing.
Q: How to get the dialog to show properly?
PS resultsDialog(a,b) is being called on a button click elsewhere.
Here's my code for the Alert dialog:
Future<void> resultsDialog(String sq, String sl) async {
BuildContext ctx;
CustomAlertDialog dialog = new CustomAlertDialog(
content: Material(
type: MaterialType.card,
child: new Container(
margin: EdgeInsets.only(left: 26.0, right: 26.0),
decoration: new BoxDecoration(
shape: BoxShape.rectangle,
color: const Color(0xFFFFFF),
borderRadius:
new BorderRadius.all(new Radius.circular(32.0)),
),
child: new Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
// dialog top
new Expanded(
//...
),
// dialog center row
new Expanded(
//...
),
// dialog bottom row
new Expanded(
//...
),
],
),
),
),
);
customShowDialog(context: ctx, child: dialog);
}
Expected result:
PS I got the inner rows takes care of so the problem here is only getting the dialog to show up and prevent it from being dismissed that's all
You need to pass context from your parent widget
and in your resultsDialog add a parameter BuildContext ctx
You can copy paste run full code below
code snippet
void _incrementCounter() {
resultsDialog(context, "a", "b");
setState(() {
Future<void> resultsDialog(BuildContext ctx, String sq, String sl) async {
//BuildContext ctx;
CustomAlertDialog dialog = new CustomAlertDialog(
content: Material(
type: MaterialType.card,
child: new Container(
margin: EdgeInsets.only(left: 26.0, right: 26.0),
decoration: new BoxDecoration(
shape: BoxShape.rectangle,
color: const Color(0xFFFFFF),
borderRadius:
new BorderRadius.all(new Radius.circular(32.0)),
),
child: new Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
// dialog top
Text('Dialog OK'),
Text('${sq}'),
Text('${sl}'),
],
),
),
),
);
customShowDialog(context: ctx, child: dialog);
}
working demo
full code
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
resultsDialog(context, "a", "b");
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
#override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Future<void> resultsDialog(BuildContext ctx, String sq, String sl) async {
//BuildContext ctx;
CustomAlertDialog dialog = new CustomAlertDialog(
content: Material(
type: MaterialType.card,
child: new Container(
margin: EdgeInsets.only(left: 26.0, right: 26.0),
decoration: new BoxDecoration(
shape: BoxShape.rectangle,
color: const Color(0xFFFFFF),
borderRadius:
new BorderRadius.all(new Radius.circular(32.0)),
),
child: new Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
// dialog top
Text('Dialog OK'),
Text('${sq}'),
Text('${sl}'),
],
),
),
),
);
customShowDialog(context: ctx, child: dialog);
}
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Examples can assume:
// enum Department { treasury, state }
/// A material design dialog.
///
/// This dialog widget does not have any opinion about the contents of the
/// dialog. Rather than using this widget directly, consider using [AlertDialog]
/// or [SimpleDialog], which implement specific kinds of material design
/// dialogs.
///
/// See also:
///
/// * [AlertDialog], for dialogs that have a message and some buttons.
/// * [SimpleDialog], for dialogs that offer a variety of options.
/// * [showDialog], which actually displays the dialog and returns its result.
/// * <https://material.google.com/components/dialogs.html>
class Dialog extends StatelessWidget {
/// Creates a dialog.
///
/// Typically used in conjunction with [showDialog].
const Dialog({
Key key,
this.child,
this.insetAnimationDuration: const Duration(milliseconds: 100),
this.insetAnimationCurve: Curves.decelerate,
}) : super(key: key);
/// The widget below this widget in the tree.
///
/// {#macro flutter.widgets.child}
final Widget child;
/// The duration of the animation to show when the system keyboard intrudes
/// into the space that the dialog is placed in.
///
/// Defaults to 100 milliseconds.
final Duration insetAnimationDuration;
/// The curve to use for the animation shown when the system keyboard intrudes
/// into the space that the dialog is placed in.
///
/// Defaults to [Curves.fastOutSlowIn].
final Curve insetAnimationCurve;
Color _getColor(BuildContext context) {
return Theme.of(context).dialogBackgroundColor;
}
#override
Widget build(BuildContext context) {
return new AnimatedPadding(
padding: MediaQuery.of(context).viewInsets +
const EdgeInsets.symmetric(horizontal: 40.0, vertical: 24.0),
duration: insetAnimationDuration,
curve: insetAnimationCurve,
child: new MediaQuery.removeViewInsets(
removeLeft: true,
removeTop: true,
removeRight: true,
removeBottom: true,
context: context,
child: new Center(
child: new ConstrainedBox(
constraints: const BoxConstraints(minWidth: 280.0),
child: new Material(
borderRadius: BorderRadius.all(Radius.circular(20.0)),
elevation: 30.0,
color: _getColor(context),
type: MaterialType.card,
child: child,
),
),
),
),
);
}
}
/// A material design alert dialog.
///
/// An alert dialog informs the user about situations that require
/// acknowledgement. An alert dialog has an optional title and an optional list
/// of actions. The title is displayed above the content and the actions are
/// displayed below the content.
///
/// If the content is too large to fit on the screen vertically, the dialog will
/// display the title and the actions and let the content overflow. Consider
/// using a scrolling widget, such as [ListView], for [content] to avoid
/// overflow.
///
/// For dialogs that offer the user a choice between several options, consider
/// using a [SimpleDialog].
///
/// Typically passed as the child widget to [showDialog], which displays the
/// dialog.
///
/// ## Sample code
///
/// This snippet shows a method in a [State] which, when called, displays a dialog box
/// and returns a [Future] that completes when the dialog is dismissed.
///
/// ```dart
/// Future<Null> _neverSatisfied() async {
/// return showDialog<Null>(
/// context: context,
/// barrierDismissible: false, // user must tap button!
/// builder: (BuildContext context) {
/// return new AlertDialog(
/// title: new Text('Rewind and remember'),
/// content: new SingleChildScrollView(
/// child: new ListBody(
/// children: <Widget>[
/// new Text('You will never be satisfied.'),
/// new Text('You\โre like me. Iโm never satisfied.'),
/// ],
/// ),
/// ),
/// actions: <Widget>[
/// new FlatButton(
/// child: new Text('Regret'),
/// onPressed: () {
/// Navigator.of(context).pop();
/// },
/// ),
/// ],
/// );
/// },
/// );
/// }
/// ```
///
/// See also:
///
/// * [SimpleDialog], which handles the scrolling of the contents but has no [actions].
/// * [Dialog], on which [AlertDialog] and [SimpleDialog] are based.
/// * [showDialog], which actually displays the dialog and returns its result.
/// * <https://material.google.com/components/dialogs.html#dialogs-alerts>
class CustomAlertDialog extends StatelessWidget {
/// Creates an alert dialog.
///
/// Typically used in conjunction with [showDialog].
///
/// The [contentPadding] must not be null. The [titlePadding] defaults to
/// null, which implies a default that depends on the values of the other
/// properties. See the documentation of [titlePadding] for details.
const CustomAlertDialog({
Key key,
this.title,
this.titlePadding,
this.content,
this.contentPadding: const EdgeInsets.fromLTRB(24.0, 20.0, 24.0, 24.0),
this.actions,
this.semanticLabel,
}) : assert(contentPadding != null),
super(key: key);
/// The (optional) title of the dialog is displayed in a large font at the top
/// of the dialog.
///
/// Typically a [Text] widget.
final Widget title;
/// Padding around the title.
///
/// If there is no title, no padding will be provided. Otherwise, this padding
/// is used.
///
/// This property defaults to providing 24 pixels on the top, left, and right
/// of the title. If the [content] is not null, then no bottom padding is
/// provided (but see [contentPadding]). If it _is_ null, then an extra 20
/// pixels of bottom padding is added to separate the [title] from the
/// [actions].
final EdgeInsetsGeometry titlePadding;
/// The (optional) content of the dialog is displayed in the center of the
/// dialog in a lighter font.
///
/// Typically, this is a [ListView] containing the contents of the dialog.
/// Using a [ListView] ensures that the contents can scroll if they are too
/// big to fit on the display.
final Widget content;
/// Padding around the content.
///
/// If there is no content, no padding will be provided. Otherwise, padding of
/// 20 pixels is provided above the content to separate the content from the
/// title, and padding of 24 pixels is provided on the left, right, and bottom
/// to separate the content from the other edges of the dialog.
final EdgeInsetsGeometry contentPadding;
/// The (optional) set of actions that are displayed at the bottom of the
/// dialog.
///
/// Typically this is a list of [FlatButton] widgets.
///
/// These widgets will be wrapped in a [ButtonBar], which introduces 8 pixels
/// of padding on each side.
///
/// If the [title] is not null but the [content] _is_ null, then an extra 20
/// pixels of padding is added above the [ButtonBar] to separate the [title]
/// from the [actions].
final List<Widget> actions;
/// The semantic label of the dialog used by accessibility frameworks to
/// announce screen transitions when the dialog is opened and closed.
///
/// If this label is not provided, a semantic label will be infered from the
/// [title] if it is not null. If there is no title, the label will be taken
/// from [MaterialLocalizations.alertDialogLabel].
///
/// See also:
///
/// * [SemanticsConfiguration.isRouteName], for a description of how this
/// value is used.
final String semanticLabel;
#override
Widget build(BuildContext context) {
final List<Widget> children = <Widget>[];
String label = semanticLabel;
if (title != null) {
children.add(new Padding(
padding: titlePadding ??
new EdgeInsets.fromLTRB(
24.0, 24.0, 24.0, content == null ? 20.0 : 0.0),
child: new DefaultTextStyle(
style: Theme.of(context).textTheme.title,
child: new Semantics(child: title, namesRoute: true),
),
));
} else {
switch (defaultTargetPlatform) {
case TargetPlatform.iOS:
label = semanticLabel;
break;
case TargetPlatform.android:
case TargetPlatform.fuchsia:
label = semanticLabel ??
MaterialLocalizations.of(context)?.alertDialogLabel;
}
}
if (content != null) {
children.add(new Flexible(
child: new Padding(
padding: contentPadding,
child: new DefaultTextStyle(
style: Theme.of(context).textTheme.subhead,
child: content,
),
),
));
}
if (actions != null) {
children.add(new ButtonTheme.bar(
child: new ButtonBar(
children: actions,
),
));
}
Widget dialogChild = new IntrinsicWidth(
child: new Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: children,
),
);
if (label != null)
dialogChild =
new Semantics(namesRoute: true, label: label, child: dialogChild);
return new Dialog(child: dialogChild);
}
}
/// An option used in a [SimpleDialog].
///
/// A simple dialog offers the user a choice between several options. This
/// widget is commonly used to represent each of the options. If the user
/// selects this option, the widget will call the [onPressed] callback, which
/// typically uses [Navigator.pop] to close the dialog.
///
/// The padding on a [SimpleDialogOption] is configured to combine with the
/// default [SimpleDialog.contentPadding] so that each option ends up 8 pixels
/// from the other vertically, with 20 pixels of spacing between the dialog's
/// title and the first option, and 24 pixels of spacing between the last option
/// and the bottom of the dialog.
///
/// ## Sample code
///
/// ```dart
/// new SimpleDialogOption(
/// onPressed: () { Navigator.pop(context, Department.treasury); },
/// child: const Text('Treasury department'),
/// )
/// ```
///
/// See also:
///
/// * [SimpleDialog], for a dialog in which to use this widget.
/// * [showDialog], which actually displays the dialog and returns its result.
/// * [FlatButton], which are commonly used as actions in other kinds of
/// dialogs, such as [AlertDialog]s.
/// * <https://material.google.com/components/dialogs.html#dialogs-simple-dialogs>
class SimpleDialogOption extends StatelessWidget {
/// Creates an option for a [SimpleDialog].
const SimpleDialogOption({
Key key,
this.onPressed,
this.child,
}) : super(key: key);
/// The callback that is called when this option is selected.
///
/// If this is set to null, the option cannot be selected.
///
/// When used in a [SimpleDialog], this will typically call [Navigator.pop]
/// with a value for [showDialog] to complete its future with.
final VoidCallback onPressed;
/// The widget below this widget in the tree.
///
/// Typically a [Text] widget.
final Widget child;
#override
Widget build(BuildContext context) {
return new InkWell(
onTap: onPressed,
child: new Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 24.0),
child: child),
);
}
}
/// A simple material design dialog.
///
/// A simple dialog offers the user a choice between several options. A simple
/// dialog has an optional title that is displayed above the choices.
///
/// Choices are normally represented using [SimpleDialogOption] widgets. If
/// other widgets are used, see [contentPadding] for notes regarding the
/// conventions for obtaining the spacing expected by Material Design.
///
/// For dialogs that inform the user about a situation, consider using an
/// [AlertDialog].
///
/// Typically passed as the child widget to [showDialog], which displays the
/// dialog.
///
/// ## Sample code
///
/// In this example, the user is asked to select between two options. These
/// options are represented as an enum. The [showDialog] method here returns
/// a [Future] that completes to a value of that enum. If the user cancels
/// the dialog (e.g. by hitting the back button on Android, or tapping on the
/// mask behind the dialog) then the future completes with the null value.
///
/// The return value in this example is used as the index for a switch statement.
/// One advantage of using an enum as the return value and then using that to
/// drive a switch statement is that the analyzer will flag any switch statement
/// that doesn't mention every value in the enum.
///
/// ```dart
/// Future<Null> _askedToLead() async {
/// switch (await showDialog<Department>(
/// context: context,
/// builder: (BuildContext context) {
/// return new SimpleDialog(
/// title: const Text('Select assignment'),
/// children: <Widget>[
/// new SimpleDialogOption(
/// onPressed: () { Navigator.pop(context, Department.treasury); },
/// child: const Text('Treasury department'),
/// ),
/// new SimpleDialogOption(
/// onPressed: () { Navigator.pop(context, Department.state); },
/// child: const Text('State department'),
/// ),
/// ],
/// );
/// }
/// )) {
/// case Department.treasury:
/// // Let's go.
/// // ...
/// break;
/// case Department.state:
/// // ...
/// break;
/// }
/// }
/// ```
///
/// See also:
///
/// * [SimpleDialogOption], which are options used in this type of dialog.
/// * [AlertDialog], for dialogs that have a row of buttons below the body.
/// * [Dialog], on which [SimpleDialog] and [AlertDialog] are based.
/// * [showDialog], which actually displays the dialog and returns its result.
/// * <https://material.google.com/components/dialogs.html#dialogs-simple-dialogs>
class SimpleDialog extends StatelessWidget {
/// Creates a simple dialog.
///
/// Typically used in conjunction with [showDialog].
///
/// The [titlePadding] and [contentPadding] arguments must not be null.
const SimpleDialog({
Key key,
this.title,
this.titlePadding: const EdgeInsets.fromLTRB(24.0, 24.0, 24.0, 0.0),
this.children,
this.contentPadding: const EdgeInsets.fromLTRB(0.0, 12.0, 0.0, 16.0),
this.semanticLabel,
}) : assert(titlePadding != null),
assert(contentPadding != null),
super(key: key);
/// The (optional) title of the dialog is displayed in a large font at the top
/// of the dialog.
///
/// Typically a [Text] widget.
final Widget title;
/// Padding around the title.
///
/// If there is no title, no padding will be provided.
///
/// By default, this provides the recommend Material Design padding of 24
/// pixels around the left, top, and right edges of the title.
///
/// See [contentPadding] for the conventions regarding padding between the
/// [title] and the [children].
final EdgeInsetsGeometry titlePadding;
/// The (optional) content of the dialog is displayed in a
/// [SingleChildScrollView] underneath the title.
///
/// Typically a list of [SimpleDialogOption]s.
final List<Widget> children;
/// Padding around the content.
///
/// By default, this is 12 pixels on the top and 16 pixels on the bottom. This
/// is intended to be combined with children that have 24 pixels of padding on
/// the left and right, and 8 pixels of padding on the top and bottom, so that
/// the content ends up being indented 20 pixels from the title, 24 pixels
/// from the bottom, and 24 pixels from the sides.
///
/// The [SimpleDialogOption] widget uses such padding.
///
/// If there is no [title], the [contentPadding] should be adjusted so that
/// the top padding ends up being 24 pixels.
final EdgeInsetsGeometry contentPadding;
/// The semantic label of the dialog used by accessibility frameworks to
/// announce screen transitions when the dialog is opened and closed.
///
/// If this label is not provided, a semantic label will be infered from the
/// [title] if it is not null. If there is no title, the label will be taken
/// from [MaterialLocalizations.dialogLabel].
///
/// See also:
///
/// * [SemanticsConfiguration.isRouteName], for a description of how this
/// value is used.
final String semanticLabel;
#override
Widget build(BuildContext context) {
final List<Widget> body = <Widget>[];
String label = semanticLabel;
if (title != null) {
body.add(new Padding(
padding: titlePadding,
child: new DefaultTextStyle(
style: Theme.of(context).textTheme.title,
child: new Semantics(namesRoute: true, child: title),
)));
} else {
switch (defaultTargetPlatform) {
case TargetPlatform.iOS:
label = semanticLabel;
break;
case TargetPlatform.android:
case TargetPlatform.fuchsia:
label =
semanticLabel ?? MaterialLocalizations.of(context)?.dialogLabel;
}
}
if (children != null) {
body.add(new Flexible(
child: new SingleChildScrollView(
padding: contentPadding,
child: new ListBody(children: children),
)));
}
Widget dialogChild = new IntrinsicWidth(
stepWidth: 56.0,
child: new ConstrainedBox(
constraints: const BoxConstraints(minWidth: 280.0),
child: new Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: body,
),
),
);
if (label != null)
dialogChild = new Semantics(
namesRoute: true,
label: label,
child: dialogChild,
);
return new Dialog(child: dialogChild);
}
}
class _DialogRoute<T> extends PopupRoute<T> {
_DialogRoute({
#required this.theme,
bool barrierDismissible: true,
this.barrierLabel,
#required this.child,
RouteSettings settings,
}) : assert(barrierDismissible != null),
_barrierDismissible = barrierDismissible,
super(settings: settings);
final Widget child;
final ThemeData theme;
#override
Duration get transitionDuration => const Duration(milliseconds: 150);
#override
bool get barrierDismissible => _barrierDismissible;
final bool _barrierDismissible;
#override
Color get barrierColor => Colors.black54;
#override
final String barrierLabel;
#override
Widget buildPage(BuildContext context, Animation<double> animation,
Animation<double> secondaryAnimation) {
return new SafeArea(
child: new Builder(builder: (BuildContext context) {
final Widget annotatedChild = new Semantics(
child: child,
scopesRoute: true,
explicitChildNodes: true,
);
return theme != null
? new Theme(data: theme, child: annotatedChild)
: annotatedChild;
}),
);
}
#override
Widget buildTransitions(BuildContext context, Animation<double> animation,
Animation<double> secondaryAnimation, Widget child) {
return new FadeTransition(
opacity: new CurvedAnimation(parent: animation, curve: Curves.easeOut),
child: child);
}
}
/// Displays a dialog above the current contents of the app.
///
/// This function takes a `builder` which typically builds a [Dialog] widget.
/// Content below the dialog is dimmed with a [ModalBarrier]. This widget does
/// not share a context with the location that `showDialog` is originally
/// called from. Use a [StatefulBuilder] or a custom [StatefulWidget] if the
/// dialog needs to update dynamically.
///
/// The `context` argument is used to look up the [Navigator] and [Theme] for
/// the dialog. It is only used when the method is called. Its corresponding
/// widget can be safely removed from the tree before the dialog is closed.
///
/// The `child` argument is deprecated, and should be replaced with `builder`.
///
/// Returns a [Future] that resolves to the value (if any) that was passed to
/// [Navigator.pop] when the dialog was closed.
///
/// The dialog route created by this method is pushed to the root navigator.
/// If the application has multiple [Navigator] objects, it may be necessary to
/// call `Navigator.of(context, rootNavigator: true).pop(result)` to close the
/// dialog rather just 'Navigator.pop(context, result)`.
///
/// See also:
/// * [AlertDialog], for dialogs that have a row of buttons below a body.
/// * [SimpleDialog], which handles the scrolling of the contents and does
/// not show buttons below its body.
/// * [Dialog], on which [SimpleDialog] and [AlertDialog] are based.
/// * <https://material.google.com/components/dialogs.html>
Future<T> customShowDialog<T>({
#required
BuildContext context,
bool barrierDismissible: true,
#Deprecated(
'Instead of using the "child" argument, return the child from a closure '
'provided to the "builder" argument. This will ensure that the BuildContext '
'is appropriate for widgets built in the dialog.')
Widget child,
WidgetBuilder builder,
}) {
assert(child == null || builder == null);
return Navigator.of(context, rootNavigator: true).push(new _DialogRoute<T>(
child: child ?? new Builder(builder: builder),
theme: Theme.of(context, shadowThemeOnly: true),
barrierDismissible: barrierDismissible,
barrierLabel:
MaterialLocalizations.of(context).modalBarrierDismissLabel,
));
}
Related
PageView inside SliverChildBuilderDelegate starting at last page when scrolling fast
I needed a floating SliverAppBar with TabBarView. Each tab has a CustomScrollView to scroll it's Childs. If i put PageView as a child and i scroll fast then the PageView starts with last page instead of first page. I found a sample code here in flutter docs: https://api.flutter.dev/flutter/widgets/NestedScrollView-class.html And i just changed the ListTile inside the SliverChildBuilderDelegate with a PageView. But when i test this code and scroll fast the pageView starts with last page. Here's a demo of that https://gyazo.com/79709286236fa3dbf1f88b1e92f5cee3 And here's my code: // This example shows a [NestedScrollView] whose header is the combination of a // [TabBar] in a [SliverAppBar] and whose body is a [TabBarView]. It uses a // [SliverOverlapAbsorber]/[SliverOverlapInjector] pair to make the inner lists // align correctly, and it uses [SafeArea] to avoid any horizontal disturbances // (e.g. the "notch" on iOS when the phone is horizontal). In addition, // [PageStorageKey]s are used to remember the scroll position of each tab's // list. import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); /// This is the main application widget. class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); static const String _title = 'Flutter Code Sample'; #override Widget build(BuildContext context) { return const MaterialApp( title: _title, home: MyStatelessWidget(), ); } } /// This is the stateless widget that the main application instantiates. class MyStatelessWidget extends StatelessWidget { const MyStatelessWidget({Key? key}) : super(key: key); #override Widget build(BuildContext context) { final List<String> _tabs = <String>['Tab 1', 'Tab 2']; return DefaultTabController( length: _tabs.length, // This is the number of tabs. child: Scaffold( body: NestedScrollView( headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { // These are the slivers that show up in the "outer" scroll view. return <Widget>[ SliverOverlapAbsorber( // This widget takes the overlapping behavior of the SliverAppBar, // and redirects it to the SliverOverlapInjector below. If it is // missing, then it is possible for the nested "inner" scroll view // below to end up under the SliverAppBar even when the inner // scroll view thinks it has not been scrolled. // This is not necessary if the "headerSliverBuilder" only builds // widgets that do not overlap the next sliver. handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), sliver: SliverAppBar( title: const Text('Books'), // This is the title in the app bar. pinned: true, floating: true, expandedHeight: 150.0, // The "forceElevated" property causes the SliverAppBar to show // a shadow. The "innerBoxIsScrolled" parameter is true when the // inner scroll view is scrolled beyond its "zero" point, i.e. // when it appears to be scrolled below the SliverAppBar. // Without this, there are cases where the shadow would appear // or not appear inappropriately, because the SliverAppBar is // not actually aware of the precise position of the inner // scroll views. forceElevated: innerBoxIsScrolled, bottom: TabBar( // These are the widgets to put in each tab in the tab bar. tabs: _tabs.map((String name) => Tab(text: name)).toList(), ), ), ), ]; }, body: TabBarView( // These are the contents of the tab views, below the tabs. children: _tabs.map((String name) { return SafeArea( top: false, bottom: false, child: Builder( // This Builder is needed to provide a BuildContext that is // "inside" the NestedScrollView, so that // sliverOverlapAbsorberHandleFor() can find the // NestedScrollView. builder: (BuildContext context) { return CustomScrollView( // The "controller" and "primary" members should be left // unset, so that the NestedScrollView can control this // inner scroll view. // If the "controller" property is set, then this scroll // view will not be associated with the NestedScrollView. // The PageStorageKey should be unique to this ScrollView; // it allows the list to remember its scroll position when // the tab view is not on the screen. key: PageStorageKey<String>(name), slivers: <Widget>[ SliverOverlapInjector( // This is the flip side of the SliverOverlapAbsorber // above. handle: NestedScrollView.sliverOverlapAbsorberHandleFor( context), ), SliverPadding( padding: const EdgeInsets.all(8.0), // In this example, the inner scroll view has // fixed-height list items, hence the use of // SliverFixedExtentList. However, one could use any // sliver widget here, e.g. SliverList or SliverGrid. sliver: SliverFixedExtentList( // The items in this example are fixed to 48 pixels // high. This matches the Material Design spec for // ListTile widgets. itemExtent: 48.0, delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { // This builder is called for each child. // In this example, we just number each list item. return PageView( /// [PageView.scrollDirection] defaults to [Axis.horizontal]. /// Use [Axis.vertical] to scroll vertically. scrollDirection: Axis.horizontal, children: const <Widget>[ Center( child: Text('First Page'), ), Center( child: Text('Second Page'), ), Center( child: Text('Third Page'), ) ], ); }, // The childCount of the SliverChildBuilderDelegate // specifies how many children this inner list // has. In this example, each tab has a list of // exactly 30 items, but this is arbitrary. childCount: 100, ), ), ), ], ); }, ), ); }).toList(), ), ), ), ); } } How can i make the pageView to starts with first page? I tried setting this to pageView controller: PageController(initialPage: 0), But it didn't work.
Flutter gesture detector in ReorderableListview not working
In my flutter app, the reorderable listview is preventing the child gesture detectors from triggering ontap. some unimportant code has been removed for privacy reasons. How can I make this work? Thanks - Joseph Container( height: 600, child: ReorderableListView( onReorder: (oldIndex, newIndex) async { ... }, children: [ for (var line in orderedLines) ...[ GestureDetector( key: ValueKey(line.name), onTap: () { print("yay"); },
FrontMobe's answer has helped me. But in my case i needed the default mobile (delayed drag start) behavior, which i achieved by using ReorderableDelayedDragStartListener as the listener. ReorderableListView.builder( buildDefaultDragHandles: false, // ... itemBuilder: (context, index) { return ReorderableDelayedDragStartListener( index: index, child: ... ); )
I found the following in the documentation. It worked for me. Just set buildDefaultDragHandles to false and use a ReorderableDragStartListener. /// If true: on desktop platforms, a drag handle is stacked over the /// center of each item's trailing edge; on mobile platforms, a long /// press anywhere on the item starts a drag. /// /// The default desktop drag handle is just an [Icons.drag_handle] /// wrapped by a [ReorderableDragStartListener]. On mobile /// platforms, the entire item is wrapped with a /// [ReorderableDelayedDragStartListener]. /// /// To change the appearance or the layout of the drag handles, make /// this parameter false and wrap each list item, or a widget within /// each list item, with [ReorderableDragStartListener] or /// [ReorderableDelayedDragStartListener], or a custom subclass /// of [ReorderableDragStartListener]. /// /// The following sample specifies `buildDefaultDragHandles: false`, and /// uses a [Card] at the leading edge of each item for the item's drag handle. /// /// {#tool dartpad --template=stateful_widget_scaffold} /// /// ```dart /// final List<int> _items = List<int>.generate(50, (int index) => index); /// /// #override /// Widget build(BuildContext context){ /// final ColorScheme colorScheme = Theme.of(context).colorScheme; /// final Color oddItemColor = colorScheme.primary.withOpacity(0.05); /// final Color evenItemColor = colorScheme.primary.withOpacity(0.15); /// /// return ReorderableListView( /// buildDefaultDragHandles: false, /// children: <Widget>[ /// for (int index = 0; index < _items.length; index++) /// Container( /// key: Key('$index'), /// color: _items[index].isOdd ? oddItemColor : evenItemColor, /// child: Row( /// children: <Widget>[ /// Container( /// width: 64, /// height: 64, /// padding: const EdgeInsets.all(8), /// child: ReorderableDragStartListener( /// index: index, /// child: Card( /// color: colorScheme.primary, /// elevation: 2, /// ), /// ), /// ), /// Text('Item ${_items[index]}'), /// ], /// ), /// ), /// ], /// onReorder: (int oldIndex, int newIndex) { /// setState(() { /// if (oldIndex < newIndex) { /// newIndex -= 1; /// } /// final int item = _items.removeAt(oldIndex); /// _items.insert(newIndex, item); /// }); /// }, /// ); /// } /// ``` ///{#end-tool}
Flutter - Error: The argument type 'String/*1*/' can't be assigned to the parameter type 'String/*2*/'
String selectedValue; Widget _dropDownMenu<String>({String title, List<String> list, List<String> strList, Function(String) onChange}) { return Container( decoration: containerDecoration(border: Border.all(color: Colors.grey)), width: MediaQuery.of(context).size.width - 20, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ SizedBox(width: 10), Container( width: MediaQuery.of(context).size.width - 60, child: DropdownButtonHideUnderline( child: DropdownButton<String>( value: selectedValue, hint: Text(title), items: List.generate(list.length, (index) { return DropdownMenuItem<String>( value: list[index], child: Text(strList[index], key: UniqueKey()), ); }), onChanged: (value) { setState(() { selectedValue = value; onChange(value); }); } ) ), ), SizedBox(width: 10) ] ) ); } this code give me this message lib/src/ui/Filter_page.dart:136:24: Error: The argument type 'String/1/' can't be assigned to the parameter type 'String/2/'. - 'String/1/' is from 'dart:core'. - 'String/2/' is from 'package:fundaqah_flutter/src/ui/Filter_page.dart' ('lib/src/ui/Filter_page.dart'). Try changing the type of the parameter, or casting the argument to 'String/2/'. value: selectedValue, and .toString() not working
Please remove <String> and error will disappear _dropDownMenu<String>({String title to Widget _dropDownMenu({String title for test, I update some Container width, you can see full test code full test code import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. #override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( // This is the theme of your application. // // Try running your application with "flutter run". You'll see the // application has a blue toolbar. Then, without quitting the app, try // changing the primarySwatch below to Colors.green and then invoke // "hot reload" (press "r" in the console where you ran "flutter run", // or simply save your changes to "hot reload" in a Flutter IDE). // Notice that the counter didn't reset back to zero; the application // is not restarted. primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); // This widget is the home page of your application. It is stateful, meaning // that it has a State object (defined below) that contains fields that affect // how it looks. // This class is the configuration for the state. It holds the values (in this // case the title) provided by the parent (in this case the App widget) and // used by the build method of the State. Fields in a Widget subclass are // always marked "final". final String title; #override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { // This call to setState tells the Flutter framework that something has // changed in this State, which causes it to rerun the build method below // so that the display can reflect the updated values. If we changed // _counter without calling setState(), then the build method would not be // called again, and so nothing would appear to happen. _counter++; }); } String selectedValue; Widget _dropDownMenu( {String title, List<String> list, List<String> strList, Function(String) onChange}) { return Container( //decoration: containerDecoration(border: Border.all(color: Colors.grey)), //height: 100, //width: MediaQuery.of(context).size.width - 20, child: Row(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ SizedBox(width: 10), Container( //width: MediaQuery.of(context).size.width - 60, child: DropdownButtonHideUnderline( child: DropdownButton<String>( value: selectedValue, hint: Text(title), items: List.generate(list.length, (index) { return DropdownMenuItem<String>( value: list[index], child: Text(strList[index], key: UniqueKey()), ); }), onChanged: (String value) { setState(() { selectedValue = value; onChange(value); }); })), ), SizedBox(width: 10) ])); } #override Widget build(BuildContext context) { // This method is rerun every time setState is called, for instance as done // by the _incrementCounter method above. // // The Flutter framework has been optimized to make rerunning build methods // fast, so that you can just rebuild anything that needs updating rather // than having to individually change instances of widgets. return Scaffold( appBar: AppBar( // Here we take the value from the MyHomePage object that was created by // the App.build method, and use it to set our appbar title. title: Text(widget.title), ), body: Center( // Center is a layout widget. It takes a single child and positions it // in the middle of the parent. child: Column( // Column is also a layout widget. It takes a list of children and // arranges them vertically. By default, it sizes itself to fit its // children horizontally, and tries to be as tall as its parent. // // Invoke "debug painting" (press "p" in the console, choose the // "Toggle Debug Paint" action from the Flutter Inspector in Android // Studio, or the "Toggle Debug Paint" command in Visual Studio Code) // to see the wireframe for each widget. // // Column has various properties to control how it sizes itself and // how it positions its children. Here we use mainAxisAlignment to // center the children vertically; the main axis here is the vertical // axis because Columns are vertical (the cross axis would be // horizontal). mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ _dropDownMenu( title: "", list: ["a", "b"], strList: ["a", "b"], onChange: (value) => {print("CLICKED")} ), Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.display1, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ); } }
How to open a web view of a link from an api?
See the image first: enter image description here So i have made a news app using https://newsapi.org/s/google-news-in-api Code: Widget build(BuildContext context) { return Container( child: Center( child: isLoading ? CircularProgressIndicator() : ListView.builder( itemCount: newsData == null ? 0 : newsData.length, itemBuilder: (context, int index) { return GestureDetector( onTap: () => Navigator.of(context).pushNamed("/headlines"), child: Card( margin: EdgeInsets.all(10), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(15), ), elevation: 5, child: Column( children: <Widget>[ ClipRRect( borderRadius: BorderRadius.only( topLeft: Radius.circular(15), topRight: Radius.circular(15), ), child: Image.network(newsData[index]['urlToImage']), ), Padding( padding: const EdgeInsets.all(8.0), child: Text( newsData[index]['title'], style: TextStyle( fontSize: 23.0, fontWeight: FontWeight.bold), ), ), Padding( padding: const EdgeInsets.all(8.0), child: Align( alignment: Alignment.bottomLeft, child: Text( newsData[index]['publishedAt'][11] ), ), ) ], ), semanticContainer: false, color: Colors.white70, ), ); }, ), So how can i open the news website when the card is clicked/tapped in this app itself, I mean how should i open the news website in this app rather than open it up in the browser using url_launcher Note: I found a plugin "flutter_webview_plugin" But still not able to implement it. Also do remember that I need to keep the index number common for both the card and the source url.
Edit add click event to image https://inducesmile.com/google-flutter/how-to-add-on-click-event-to-image-in-flutter/ You can wrap you news image with GestureDetector and do action in onTap GestureDetector( onTap: () { Navigator.push(context, MaterialPageRoute(builder: (BuildContext context) => MyInAppWebView(webUrl: newsData[index][url],webRect: Rect.fromLTWH(0, 0, 300, 300)))); ); }, child: CircleAvatar( backgroundImage: ExactAssetImage('assets/images/umbrella.png'), minRadius: 80, maxRadius: 120, ), ), You can use https://pub.dev/packages/flutter_inappbrowser You can display in widget directly or Navigator.push(context, MaterialPageRoute(builder: (BuildContext context) => MyInAppWebView(webUrl: "https://flutter.dev/",webRect: Rect.fromLTWH(0, 0, 300, 300)))); You can reference both situations in my full code the simple MyInAppWebView just pass webUrl and WebRect or you can reference complex demo (picture 2) in official site class MyInAppWebView extends StatelessWidget { String webUrl; final Rect webRect; InAppWebViewController webView; MyInAppWebView({Key key, this.webUrl, this.webRect}) : super(key: key); #override Widget build(BuildContext context) { InAppWebView webWidget = new InAppWebView( initialUrl: webUrl, initialHeaders: {}, initialOptions: {}, onWebViewCreated: (InAppWebViewController controller) { webView = controller; }, onLoadStart: (InAppWebViewController controller, String url) { print("InAppWebView.onLoadStart: $url"); this.webUrl = url; }, onProgressChanged: (InAppWebViewController controller, int progress) { double prog = progress / 100; print('InAppWebView.onProgressChanged: $prog'); }); return Container( width: webRect.width, height: webRect.height, child: webWidget, ); } } full code import 'package:flutter/material.dart'; import 'package:flutter_inappbrowser/flutter_inappbrowser.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. #override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( // This is the theme of your application. // // Try running your application with "flutter run". You'll see the // application has a blue toolbar. Then, without quitting the app, try // changing the primarySwatch below to Colors.green and then invoke // "hot reload" (press "r" in the console where you ran "flutter run", // or simply save your changes to "hot reload" in a Flutter IDE). // Notice that the counter didn't reset back to zero; the application // is not restarted. primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); // This widget is the home page of your application. It is stateful, meaning // that it has a State object (defined below) that contains fields that affect // how it looks. // This class is the configuration for the state. It holds the values (in this // case the title) provided by the parent (in this case the App widget) and // used by the build method of the State. Fields in a Widget subclass are // always marked "final". final String title; #override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { Navigator.push(context, MaterialPageRoute(builder: (BuildContext context) => MyInAppWebView(webUrl: "https://flutter.dev/",webRect: Rect.fromLTWH(0, 0, 300, 300)))); // This call to setState tells the Flutter framework that something has // changed in this State, which causes it to rerun the build method below // so that the display can reflect the updated values. If we changed // _counter without calling setState(), then the build method would not be // called again, and so nothing would appear to happen. _counter++; }); } #override Widget build(BuildContext context) { // This method is rerun every time setState is called, for instance as done // by the _incrementCounter method above. // // The Flutter framework has been optimized to make rerunning build methods // fast, so that you can just rebuild anything that needs updating rather // than having to individually change instances of widgets. return Scaffold( appBar: AppBar( // Here we take the value from the MyHomePage object that was created by // the App.build method, and use it to set our appbar title. title: Text(widget.title), ), body: Center( // Center is a layout widget. It takes a single child and positions it // in the middle of the parent. child: Column( // Column is also a layout widget. It takes a list of children and // arranges them vertically. By default, it sizes itself to fit its // children horizontally, and tries to be as tall as its parent. // // Invoke "debug painting" (press "p" in the console, choose the // "Toggle Debug Paint" action from the Flutter Inspector in Android // Studio, or the "Toggle Debug Paint" command in Visual Studio Code) // to see the wireframe for each widget. // // Column has various properties to control how it sizes itself and // how it positions its children. Here we use mainAxisAlignment to // center the children vertically; the main axis here is the vertical // axis because Columns are vertical (the cross axis would be // horizontal). mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Expanded( child: MyInAppWebView(webUrl: "https://flutter.dev/", webRect: Rect.fromLTWH(0, 0, 300, 300),)), Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.display1, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ); } } class MyInAppWebView extends StatelessWidget { String webUrl; final Rect webRect; InAppWebViewController webView; MyInAppWebView({Key key, this.webUrl, this.webRect}) : super(key: key); #override Widget build(BuildContext context) { InAppWebView webWidget = new InAppWebView( initialUrl: webUrl, initialHeaders: {}, initialOptions: {}, onWebViewCreated: (InAppWebViewController controller) { webView = controller; }, onLoadStart: (InAppWebViewController controller, String url) { print("InAppWebView.onLoadStart: $url"); this.webUrl = url; }, onProgressChanged: (InAppWebViewController controller, int progress) { double prog = progress / 100; print('InAppWebView.onProgressChanged: $prog'); }); return Container( width: webRect.width, height: webRect.height, child: webWidget, ); } } example code demo official demo
Did you try forceWebview option as explained in https://medium.com/#muaazmusthafa08/how-to-load-a-web-page-in-flutter-app-607fa9184e4a
How to add a margin or padding to a Snackbar?
I have been working on the Snackbar and achieved in my project successfully. However, there is this little thing which I want to add to Snackbar and that is the margins. I have seen in this link : Snackbars - Material Design I really want my Snackbar to come like this : What I'm getting is this now : My code is : final snackBar = SnackBar( content: Text("Feild(s) are empty!"), duration: new Duration(seconds: 1), backgroundColor: Theme.of(context).primaryColor, ); Scaffold.of(context).showSnackBar(snackBar); }
Flutter team have updated the snackbar to match the material design in this PR. You can simply get the new behavior by setting behavior: SnackBarBehavior.floating Here is a sample code final snackBar = SnackBar( elevation: 6.0, backgroundColor: Configs.current.COLORS_PRIMARY, behavior: SnackBarBehavior.floating, content: Text( "Snack bar test", style: TextStyle(color: Colors.white), ), ); and the result will look like this
Not sure about margins. Round corner SnackBar can be created like: Scaffold .of(context) .showSnackBar( SnackBar( content: Text(message), shape: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(20))))); Use required border radius in above. Update: You can use floating SnackBar to add default margins. Pass below to SnackBar constructor: Scaffold .of(context) .showSnackBar( SnackBar( content: Text(message), behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(20)))));
Screenshot: Minimal code: var snackbar = SnackBar( content: Text('Hello World!'), margin: EdgeInsets.all(20), behavior: SnackBarBehavior.floating, ); Scaffold.of(context).showSnackBar(snackbar); Full code: #override Widget build(BuildContext context) { return Scaffold( body: Center( child: Builder(builder: (context) { return RaisedButton( onPressed: () { var snackbar = SnackBar( content: Text('Hello World!'), margin: EdgeInsets.all(20), behavior: SnackBarBehavior.floating, ); Scaffold.of(context).showSnackBar(snackbar); }, child: Text('Show SnackBar'), ); }), ), ); }
Disclaimer: This answer is outdated and should only be viewed for historical reasons. Choose an appropriate solution from above ๐ Sadly I haven't found any options or possibilities, given by Flutter, to implement a round SnackBar. If you really need/want the rounded corners and spacing you can copy the source code of the SnackBar and make your adjustments to the copy. Remember to add implements SnackBar to your class definition. I've started the implementation and added the rounded corners. You'll just have to add the bottom padding for Phones like the iPhone X, which have elements at the bottom, obscuring the view. (To get the bottom spacing you can use MediaQuery.of(context).viewInsets.bottom.) Standalone example you can copy: main.dart import 'package:flutter/material.dart'; import 'package:your_app_name/my_snack.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { #override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: MyBody() ), ); } } class MyBody extends StatelessWidget { #override Widget build(BuildContext context) { return Center( child: RaisedButton(onPressed: () { Scaffold.of(context).showSnackBar(MySnack(content: Text('MySnack!'))); }), ); } } my_snack.dart // Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter/material.dart'; const double _kSnackBarPadding = 24.0; const double _kSingleLineVerticalPadding = 14.0; const Color _kSnackBackground = Color(0xFF323232); // TODO(ianh): We should check if the given text and actions are going to fit on // one line or not, and if they are, use the single-line layout, and if not, use // the multiline layout. See link above. // TODO(ianh): Implement the Tablet version of snackbar if we're "on a tablet". const Duration _kSnackBarTransitionDuration = Duration(milliseconds: 250); const Duration _kSnackBarDisplayDuration = Duration(milliseconds: 4000); const Curve _snackBarHeightCurve = Curves.fastOutSlowIn; const Curve _snackBarFadeCurve = Interval(0.72, 1.0, curve: Curves.fastOutSlowIn); /// Specify how a [SnackBar] was closed. /// /// The [ScaffoldState.showSnackBar] function returns a /// [ScaffoldFeatureController]. The value of the controller's closed property /// is a Future that resolves to a SnackBarClosedReason. Applications that need /// to know how a snackbar was closed can use this value. /// /// Example: /// /// ```dart /// Scaffold.of(context).showSnackBar( /// SnackBar( ... ) /// ).closed.then((SnackBarClosedReason reason) { /// ... /// }); /// ``` /// A button for a [SnackBar], known as an "action". /// /// Snack bar actions are always enabled. If you want to disable a snack bar /// action, simply don't include it in the snack bar. /// /// Snack bar actions can only be pressed once. Subsequent presses are ignored. /// /// See also: /// /// * [SnackBar] /// * <https://material.io/design/components/snackbars.html> class _SnackBarActionState extends State<SnackBarAction> { bool _haveTriggeredAction = false; void _handlePressed() { if (_haveTriggeredAction) return; setState(() { _haveTriggeredAction = true; }); widget.onPressed(); Scaffold.of(context).hideCurrentSnackBar(reason: SnackBarClosedReason.action); } #override Widget build(BuildContext context) { return FlatButton( onPressed: _haveTriggeredAction ? null : _handlePressed, child: Text(widget.label), textColor: widget.textColor, disabledTextColor: widget.disabledTextColor, ); } } /// A lightweight message with an optional action which briefly displays at the /// bottom of the screen. /// /// To display a snack bar, call `Scaffold.of(context).showSnackBar()`, passing /// an instance of [SnackBar] that describes the message. /// /// To control how long the [SnackBar] remains visible, specify a [duration]. /// /// A SnackBar with an action will not time out when TalkBack or VoiceOver are /// enabled. This is controlled by [AccessibilityFeatures.accessibleNavigation]. /// /// See also: /// /// * [Scaffold.of], to obtain the current [ScaffoldState], which manages the /// display and animation of snack bars. /// * [ScaffoldState.showSnackBar], which displays a [SnackBar]. /// * [ScaffoldState.removeCurrentSnackBar], which abruptly hides the currently /// displayed snack bar, if any, and allows the next to be displayed. /// * [SnackBarAction], which is used to specify an [action] button to show /// on the snack bar. /// * <https://material.io/design/components/snackbars.html> class MySnack extends StatelessWidget implements SnackBar { /// Creates a snack bar. /// /// The [content] argument must be non-null. const MySnack({ Key key, #required this.content, this.backgroundColor, this.action, this.duration = _kSnackBarDisplayDuration, this.animation, }) : assert(content != null), assert(duration != null), super(key: key); /// The primary content of the snack bar. /// /// Typically a [Text] widget. final Widget content; /// The Snackbar's background color. By default the color is dark grey. final Color backgroundColor; /// (optional) An action that the user can take based on the snack bar. /// /// For example, the snack bar might let the user undo the operation that /// prompted the snackbar. Snack bars can have at most one action. /// /// The action should not be "dismiss" or "cancel". final SnackBarAction action; /// The amount of time the snack bar should be displayed. /// /// Defaults to 4.0s. /// /// See also: /// /// * [ScaffoldState.removeCurrentSnackBar], which abruptly hides the /// currently displayed snack bar, if any, and allows the next to be /// displayed. /// * <https://material.io/design/components/snackbars.html> final Duration duration; /// The animation driving the entrance and exit of the snack bar. final Animation<double> animation; #override Widget build(BuildContext context) { final MediaQueryData mediaQueryData = MediaQuery.of(context); assert(animation != null); final ThemeData theme = Theme.of(context); final ThemeData darkTheme = ThemeData( brightness: Brightness.dark, accentColor: theme.accentColor, accentColorBrightness: theme.accentColorBrightness, ); final List<Widget> children = <Widget>[ const SizedBox(width: _kSnackBarPadding), Expanded( child: Container( padding: const EdgeInsets.symmetric(vertical: _kSingleLineVerticalPadding), child: DefaultTextStyle( style: darkTheme.textTheme.subhead, child: content, ), ), ), ]; if (action != null) { children.add(ButtonTheme.bar( padding: const EdgeInsets.symmetric(horizontal: _kSnackBarPadding), textTheme: ButtonTextTheme.accent, child: action, )); } else { children.add(const SizedBox(width: _kSnackBarPadding)); } final CurvedAnimation heightAnimation = CurvedAnimation(parent: animation, curve: _snackBarHeightCurve); final CurvedAnimation fadeAnimation = CurvedAnimation(parent: animation, curve: _snackBarFadeCurve, reverseCurve: const Threshold(0.0)); Widget snackbar = SafeArea( bottom: false, top: false, child: Row( children: children, crossAxisAlignment: CrossAxisAlignment.center, ), ); snackbar = Semantics( container: true, liveRegion: true, onDismiss: () { Scaffold.of(context).removeCurrentSnackBar(reason: SnackBarClosedReason.dismiss); }, child: Dismissible( key: const Key('dismissible'), direction: DismissDirection.down, resizeDuration: null, onDismissed: (DismissDirection direction) { Scaffold.of(context).removeCurrentSnackBar(reason: SnackBarClosedReason.swipe); }, child: Padding( padding: const EdgeInsets.all(8.0), child: Container( decoration: BoxDecoration( color: backgroundColor ?? _kSnackBackground, borderRadius: BorderRadius.circular(8.0) ), child: Material( elevation: 6.0, color: Colors.transparent, child: Theme( data: darkTheme, child: mediaQueryData.accessibleNavigation ? snackbar : FadeTransition( opacity: fadeAnimation, child: snackbar, ), ), ), ), ), ), ); return ClipRect( child: mediaQueryData.accessibleNavigation ? snackbar : AnimatedBuilder( animation: heightAnimation, builder: (BuildContext context, Widget child) { return Align( alignment: AlignmentDirectional.topStart, heightFactor: heightAnimation.value, child: child, ); }, child: snackbar, ), ); } // API for Scaffold.addSnackBar(): /// Creates an animation controller useful for driving a snack bar's entrance and exit animation. static AnimationController createAnimationController({ #required TickerProvider vsync }) { return AnimationController( duration: _kSnackBarTransitionDuration, debugLabel: 'SnackBar', vsync: vsync, ); } /// Creates a copy of this snack bar but with the animation replaced with the given animation. /// /// If the original snack bar lacks a key, the newly created snack bar will /// use the given fallback key. SnackBar withAnimation(Animation<double> newAnimation, { Key fallbackKey }) { return MySnack( key: key ?? fallbackKey, content: content, backgroundColor: backgroundColor, action: action, duration: duration, animation: newAnimation, ); } } Changes made to SnackBar: Renamed SnackBarto MySnack Added implements SnackBar to MySnack class Set bottom: false inside the SafeArea in MySnack build method Added a Container around the Material which is the background of the SnackBar Moved the color declaration from Material to the created Container Added the desired borderRadius (together with the color) as a BoxDecoration to the Container