Flutter에서 토스트를 만드는 방법?
나는 비슷한 만들 수 토스트 떨림에를? 사용자의 정면에 있지 않고 그 뒤의보기를 잠 그거나 희미하게하지 않는 작은 알림 창일까요?
다음을 ScaffoldState
사용 하여 부모에 액세스 할 수 있습니다.Scaffold.of(context)
그런 다음 다음과 같이하십시오.
Scaffold.of(context).showSnackBar(new SnackBar(
content: new Text("Sending Message"),
));
스낵바는 머티리얼 디자인의 공식 "토스트"입니다. https://material.io/design/components/snackbars.html#usage를 참조 하십시오.
다음은 완전히 작동하는 예입니다.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: const Home(),
);
}
}
class Home extends StatelessWidget {
const Home({
Key key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Snack bar'),
),
/// We use [Builder] here to use a [context] that is a descendant of [Scaffold]
/// or else [Scaffold.of] will return null
body: Builder(
builder: (context) => Center(
child: RaisedButton(
child: const Text('Show toast'),
onPressed: () => _showToast(context),
),
),
),
);
}
void _showToast(BuildContext context) {
final scaffold = Scaffold.of(context);
scaffold.showSnackBar(
SnackBar(
content: const Text('Added to favorite'),
action: SnackBarAction(
label: 'UNDO', onPressed: scaffold.hideCurrentSnackBar),
),
);
}
}
SnackBar
Darky가 지적했듯이 확실히 사용하기에 적합한 클래스입니다.
한 가지 까다로운 점 showSnackBar
은 .NET을 생성하는 빌드 메서드 내에서 ScaffoldState
호출하려는 경우 .showSnackBar
Scaffold
문제 해결 방법을 설명하는 텍스트가 포함 된 이와 같은 오류가 표시 될 수 있습니다.
══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
The following assertion was thrown while handling a gesture:
Scaffold.of() called with a context that does not contain a Scaffold.
No Scaffold ancestor could be found starting from the context that was passed to Scaffold.of(). This
usually happens when the context provided is from the same StatefulWidget as that whose build
function actually creates the Scaffold widget being sought.
There are several ways to avoid this problem. The simplest is to use a Builder to get a context that
is "under" the Scaffold. For an example of this, please see the documentation for Scaffold.of():
https://docs.flutter.io/flutter/material/Scaffold/of.html
A more efficient solution is to split your build function into several widgets. This introduces a
new context from which you can obtain the Scaffold. In this solution, you would have an outer widget
that creates the Scaffold populated by instances of your new inner widgets, and then in these inner
widgets you would use Scaffold.of().
A less elegant but more expedient solution is assign a GlobalKey to the Scaffold, then use the
key.currentState property to obtain the ScaffoldState rather than using the Scaffold.of() function.
The context used was:
MyHomePage
When the exception was thrown, this was the stack:
#0 Scaffold.of (package:flutter/src/material/scaffold.dart:444:5)
#1 MyHomePage.build.<anonymous closure> (/Users/jackson/Library/Developer/CoreSimulator/Devices/7072C907-DBAD-44FE-8F40-0257442C51D9/data/Containers/Data/Application/77FEC1A4-1453-442C-8208-96E0323DEFB2/tmp/so_scratch2Tkq9Jb/so_scratch2/lib/main.dart:23:24)
#2 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:323:14)
#3 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:375:30)
#4 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:102:24)
#5 TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:149:9)
#6 TapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:119:7)
#7 GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27)
#8 BindingBase&SchedulerBinding&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:147:20)
#9 BindingBase&SchedulerBinding&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:121:22)
#10 BindingBase&SchedulerBinding&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:101:7)
#11 BindingBase&SchedulerBinding&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:64:7)
#12 BindingBase&SchedulerBinding&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:48:7)
#13 _invoke1 (file:///b/build/slave/Mac_Engine/build/src/flutter/lib/ui/hooks.dart:100)
#14 _dispatchPointerDataPacket (file:///b/build/slave/Mac_Engine/build/src/flutter/lib/ui/hooks.dart:58)
Handler: onTap
Recognizer:
TapGestureRecognizer#69dbc(debugOwner: GestureDetector, state: ready)
════════════════════════════════════════════════════════════════════════════════════════════════════
생성자에 GlobalKey
를 전달할 수 있습니다 Scaffold
.
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final key = new GlobalKey<ScaffoldState>();
return new Scaffold(
key: key,
floatingActionButton: new Builder(
builder: (BuildContext context) {
return new FloatingActionButton(
onPressed: () {
key.currentState.showSnackBar(new SnackBar(
content: new Text("Sending Message"),
));
},
tooltip: 'Increment',
child: new Icon(Icons.add),
);
}
),
);
}
}
또는를 사용 하여 Scaffold의 자식 Builder
을 만들 수 있습니다 BuildContext
.
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
floatingActionButton: new Builder(
builder: (BuildContext context) {
return new FloatingActionButton(
onPressed: () {
Scaffold.of(context).showSnackBar(new SnackBar(
content: new Text("Sending Message"),
));
},
tooltip: 'Increment',
child: new Icon(Icons.add),
);
}
),
);
}
}
마지막으로 위젯을 여러 클래스로 분할 할 수 있습니다. 이것이 가장 장기적인 접근 방식입니다.
이 플러그인 사용
Fluttertoast.showToast(
msg: "This is Toast messaget",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIos: 1
);
토스트 메시지를 표시하려면 flutterToast 플러그인을 사용하여이 플러그인을 사용해야합니다.
- 이 종속성을 pubspec.yaml 파일에 추가하십시오.
fluttertoast: ^3.1.0
- 패키지를 얻으려면 다음 명령을 실행해야합니다.
$ flutter packages get
- 패키지 가져 오기 :-
import 'package:fluttertoast/fluttertoast.dart';
이렇게 사용하세요
Fluttertoast.showToast(
msg: "your message",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM // also possible "TOP" and "CENTER"
backgroundColor: "#e74c3c",
textColor: '#ffffff');
지금까지 제공된 Fluttertoast 패키지가 작동하지 않는 경우 ... 그럼 토스트 를 시도해보세요 .
주름도없고 의식도 없습니다.
그냥 작동합니다.
하지만 Readme에 제공된 예제에서 버그를 발견했습니다.
Toast.show("Toast plugin app", duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
메서드에는 컨텍스트가 필요합니다. 따라서 다음과 같이 '컨텍스트'를 추가하는 것이 좋습니다.
Toast.show("Toast plugin app", context, duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
확인하실 때까지 문제가 해결되었을 가능성이 있지만 이미 PR을 제출했습니다.
패키지 flushbar를 사용하는 대체 솔루션을 제공하고 싶습니다. https://github.com/AndreHaueisen/flushbar
패키지에서 말한대로 : 사용자에게 알림을 보낼 때 추가 사용자 정의가 필요한 경우이 패키지를 사용하십시오. Android 개발자의 경우 토스트와 스낵바를 대체하도록 만들어졌습니다.
flushbar 사용에 대한 또 다른 제안 Flutter에서 navigator.pop (context) 후 스낵바 를 표시하는 방법은 무엇입니까?
flushbarPosition을 TOP 또는 BOTTOM으로 설정할 수도 있습니다.
Flushbar(
title: "Hey Ninja",
message: "Lorem Ipsum is simply dummy text of the printing and typesetting industry",
flushbarPosition: FlushbarPosition.TOP,
flushbarStyle: FlushbarStyle.FLOATING,
reverseAnimationCurve: Curves.decelerate,
forwardAnimationCurve: Curves.elasticOut,
backgroundColor: Colors.red,
boxShadows: [BoxShadow(color: Colors.blue[800], offset: Offset(0.0, 2.0), blurRadius: 3.0)],
backgroundGradient: LinearGradient(colors: [Colors.blueGrey, Colors.black]),
isDismissible: false,
duration: Duration(seconds: 4),
icon: Icon(
Icons.check,
color: Colors.greenAccent,
),
mainButton: FlatButton(
onPressed: () {},
child: Text(
"CLAP",
style: TextStyle(color: Colors.amber),
),
),
showProgressIndicator: true,
progressIndicatorBackgroundColor: Colors.blueGrey,
titleText: Text(
"Hello Hero",
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 20.0, color: Colors.yellow[600], fontFamily: "ShadowsIntoLightTwo"),
),
messageText: Text(
"You killed that giant monster in the city. Congratulations!",
style: TextStyle(fontSize: 18.0, color: Colors.green, fontFamily: "ShadowsIntoLightTwo"),
),
)..show(context);
Android 원본 그래픽 토스트의 경우 https://pub.dartlang.org/packages/fluttertoast를 사용할 수 있습니다.
Works fine on Android and iOS. enter image description here
https://pub.dev/packages/toast use this for toast this library is pretty easy to use and perfect work for ios and android,
Syntax for show Toast:
Toast.show("Toast plugin app", duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
Step 1:
dependencies:
flutter_just_toast: ^1.0.1
Step 2:
import 'package:flutter_just_toast/flutter_just_toast.dart';
Step 3:
Toast.show(
message: "Your toast message",
duration: Delay.SHORT,
textColor: Colors.black);
use this dependency: toast: ^0.1.3
then import the dependency of toast in the page : import 'package:toast/toast.dart';
then on onTap() of the widget: Toast.show("Toast plugin app", context,duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
For the ones that are looking for a Toast
what can survive the route changes the SnackBar
might not be the best option.
Have a look at Overlay
instead.
https://api.flutter.dev/flutter/widgets/Overlay-class.html
you can use this package : toast
add this line to your dependencies
toast: ^0.1.5
then use it like this :
import 'package:toast/toast.dart';
Toast.show("Toast plugin app", context, duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
Add flutter_just_toast to your dependencies in your Pubspecs.yaml
dependencies:
flutter_just_toast: ^1.0.1
Next import package into your class:
import 'package:flutter_just_toast/flutter_just_toast.dart';
Implement Toast with message
Toast.show( message: "Your toast message",
duration: Delay.SHORT,
textColor: Colors.black);
get flutter toast package here
Add this package to your project dependencies in pubspec.yaml
Then whenever you want the Toast to be shown like on a tap of a button
Toast.show("Toast plugin app", context, duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
There's no widget for toast in flutter, You can go to this plugin Usecase:
Fluttertoast.showToast(
msg: "My toast messge",
textColor: Colors.white,
toastLength: Toast.LENGTH_SHORT,
timeInSecForIos: 1,
gravity: ToastGravity.BOTTOM,
backgroundColor: Colors.indigo,);
just use SnackBar(content: Text("hello"),) inside any event like onTap and onPress
you can read more about Snackbar here https://flutter.dev/docs/cookbook/design/snackbars
You can try this-
It's really easy to implement. And you can customize the toast any way you want.
You can use something like FlutterToast
Import the lib
fluttertoast: ^2.1.4
Use like below
Fluttertoast.showToast(
msg: "Hello world",
textColor: Colors.white,
toastLength: Toast.LENGTH_SHORT,
timeInSecForIos: 1,
gravity: ToastGravity.BOTTOM,
backgroundColor: Colors.indigo,
);
Thats it..
"fluttertoast"라이브러리를 사용할 수 있습니다. 이렇게하려면 다음과 같이 pubspec.yaml 파일에 추가합니다.
dependencies:
fluttertoast: ^3.1.0
그런 다음 토스트가 필요한 dart 파일에서 해당 라이브러리를 가져오고 코드를 작성하십시오. 예를 들어, 다음 코드를 참조하십시오.
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
class ToastExample extends StatefulWidget {
@override
_ToastExampleState createState() {
return _ToastExampleState();
}
}
class _ToastExampleState extends State {
void showToast() {
Fluttertoast.showToast(
msg: 'Some text',
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIos: 1,
backgroundColor: Colors.red,
textColor: Colors.white
);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Toast Tutorial',
home: Scaffold(
appBar: AppBar(
title: Text('Toast Tutorial'),
),
body: Padding(
padding: EdgeInsets.all(15.0),
child: Center(
child: RaisedButton(
child: Text('Press to show'),
onPressed: showToast,
),
),
)
),
);
}
}
void main() => runApp(ToastExample());
참고 URL : https://stackoverflow.com/questions/45948168/how-to-create-toast-in-flutter
'Programing' 카테고리의 다른 글
ImportError : Windows에 site라는 모듈이 없습니다. (0) | 2020.08.25 |
---|---|
원격 연결을 위해 redis 포트 열기 (0) | 2020.08.25 |
PowerShell 스크립트를 사용하여 EXE 파일 실행 (0) | 2020.08.24 |
.gitignore 파일에 Django 마이그레이션 파일을 추가해야합니까? (0) | 2020.08.24 |
양식을 제출 한 후 백그라운드에서 PHP 스크립트를 어떻게 실행할 수 있습니까? (0) | 2020.08.24 |