Flutter에서 토스트를 만드는 방법?


167

Flutter 에서 토스트 와 비슷한 것을 만들 수 있습니까 ? 사용자의 얼굴에 직접 있지 않고 그 뒤에보기를 잠 그거나 희미하게하지 않는 작은 알림 창입니까?

답변:


205

다음을 ScaffoldState사용 하여 부모에게 액세스 할 수 있습니다Scaffold.of(context)

그런 다음 같은 일을

Scaffold.of(context).showSnackBar(SnackBar(
      content: 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),
      ),
    );
  }
}

1
예를 들어 onPressed 안에 어떻게 감싸 야합니까? 내가 시도했지만 화면에 아무것도 나타나지 않기 때문입니다.
aziza

글쎄, 나는 금형에 맞지 않으며 나는 "공식"이 절대를 의미하지 않는다는 것을 알고있다! 스낵 바는 실제로 내 앱 UX를 빨아들이므로 잘 유지하고 항상 오래된 플로팅 팝업 스타일 알림을 구현합니다. 사용자가 스낵바 알림을 그리워하는 것이 매우 쉽다고 생각합니다 (특히 익숙하지 않은 경우). 그러나 화면의 중앙, 상단 또는 하단에 떠 다니는 팝업을 놓치는 것은 쉽지 않습니다.
SilSur

@aziza는 Builder ()에서 버튼 위젯을 래핑하면 작동합니다
Tabrizapps

위젯 호출 showSnackBar() 에는 Scaffold부모 가 있어야합니다 .
Lahiru Chandima

80

플러그인 사용

Fluttertoast.showToast(
        msg: "This is Toast messaget",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIos: 1
    );

여기에 이미지 설명을 입력하십시오


2
먼저 pubspec.yaml 파일에 Fluttertoast 의존성을 추가해야합니다. 의존성에 대한 링크는 여기 [link] ( pub.dartlang.org/packages/fluttertoast )에 있습니다. 그럼 당신은 위의 코드를 사용할 수 있습니다
프리츠 - 플레이 메이커

Unhandled Exception: MissingPluginException(No implementation found for method showToast on channel PonnamKarthik/fluttertoast)
로빈

1
이제 작동합니다. 앱을 중지하고 디버깅하지 않고 🏃‍♂️을 실행해야합니다.)
Robin


73

SnackBar Darky가 지적한대로 사용하기에 가장 적합한 클래스입니다.

스낵바

한 까다로운 일에 대한 showSnackBar받는지고 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)
════════════════════════════════════════════════════════════════════════════════════════════════════

생성자에 a 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),
          );
        }
      ),
    );
  }
}

또는를 사용 하여 비계의 자식 인 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),
          );
        }
      ),
    );
  }
}

마지막으로 위젯을 여러 클래스로 분할 할 수 있으며 이는 가장 장기적인 접근 방식입니다.


GlobalKey를 시도, 이제이 예외가 나타납니다 :I/flutter ( 4965): The following assertion was thrown while handling a gesture: I/flutter ( 4965): type 'LabeledGlobalKey<ScaffoldState>' is not a subtype of type 'BuildContext' of 'context' where I/flutter ( 4965): LabeledGlobalKey is from package:flutter/src/widgets/framework.dart I/flutter ( 4965): ScaffoldState is from package:flutter/src/material/scaffold.dart I/flutter ( 4965): Scaffold is from package:flutter/src/material/scaffold.dart I/flutter ( 4965): BuildContext is from package:flutter/src/widgets/framework.dart
Shajeel Afzal

1
a GlobalKey가 필요한 인수로 a를 사용하고있는 것 같습니다 BuildContext. 더 많은 코드를 보지 않으면 더 이상 디버깅 할 수 없습니다. 예외가 발생하는 코드 줄을 게시하십시오. 아마 올바른 인수를 사용하지 않았을 것입니다.
Collin Jackson

2
제공 한 Builder옵션 을 사용 하면 제대로 작동 하는지 확인할 수 있습니다. 이 문제에 부딪쳐서 나를 위해 해결했습니다.
SeaFuzz

GlobalKey 메서드에 오류가 있지만 final key = new GlobalKey<ScaffoldState>();Widget 빌드 외부 에서 선언을 수행하면 문제가 해결되었습니다.
Sagar V

StackOverflow에서 가장 좋은 답변 중 하나입니다! 감사합니다 @ CollinJackson
Masterfego

13

토스트 메시지를 표시하려면 flutterToast 플러그인을 사용하여이 플러그인을 사용할 수 있습니다.

  1. 이 종속 항목을 pubspec.yaml 파일에 추가하십시오. fluttertoast: ^3.1.0
  2. 패키지를 얻으려면이 명령을 실행해야합니다 :- $ flutter packages get
  3. 패키지를 가져 오기 :- 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');

자세한 내용은 이것을 확인 하십시오


24
다른 사람이 게시 한 동일한 답변에 대답하는 대신 그의 답변을 상향 조정했을 수 있습니다.
CopsOnRoad

7

설레임 : ^ 3.1.3

import 'package:fluttertoast/fluttertoast.dart';

Fluttertoast.showToast(
        msg: "This is Center Short Toast",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIos: 1,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0
    );

어떤 코드를 넣을 위치를 설명하는 설명문을 추가하십시오. "pubspec에 패키지 추가"및 "코드에서 다음을 사용하십시오."
mlyko

6

패키지 플러시 바를 사용하는 대체 솔루션을 제공하고 싶습니다. https://github.com/AndreHaueisen/flushbar
패키지가 말한 것처럼 : 사용자에게 알릴 때 더 많은 사용자 정의가 필요한 경우이 패키지를 사용하십시오. Android 개발자의 경우 토스트와 스낵바를 대체합니다.
flushbar를 사용 하는 또 다른 제안 Flutter에서 navigator.pop (context) 다음에 snackbar를 표시하는 방법은 무엇입니까?
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);

5

lib 가져 오기

설레다 : 3.1.3

아래와 같이 사용

Fluttertoast.showToast(
msg: "Hello world",
textColor: Colors.white,
toastLength: Toast.LENGTH_SHORT,
timeInSecForIos: 1,
gravity: ToastGravity.BOTTOM,
backgroundColor: Colors.indigo,

);


4

지금까지 제공된 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을 제출했습니다.


플러그인보다이 플러그인을 선호합니다 pub.dartlang.org/packages/fluttertoast. 이것은 훨씬 더 간결하고 간결하며 사용자 정의하기 쉽습니다.
SilSur

2

플러터 앱에서 토스트를 표시하는 세 가지 방법이 있습니다.
내가 아는 세 가지 방법에 대해 말하고 어떤 것을 사용할 것인지 선택하겠습니다. 두 번째를 추천합니다.

1 : 외부 패키지 사용.

이것은 flutter 앱에서 토스트를 표시하는 가장 쉬운 방법 인 첫 번째 방법입니다.

우선 pubspec.yaml에이 패키지를 추가해야합니다

flutter_just_toast:^version_here

그런 다음 토스트를 표시하려는 파일로 패키지를 가져옵니다.

'package:flutter_just_toast/flutter_just_toast.dart';

마지막 단계는 토스트를 보여줍니다.

Toast.show( message: "Your toast message", 
           duration: Delay.SHORT, 
           textColor: Colors.black);

2 : 공식적인 방법을 사용합니다.

이 방법도 간단하지만 처리해야합니다. 나는 그것이 간단하고 깨끗하다는 것이 아닙니다.이 방법을 추천합니다.

이 방법을 위해 토스트를 보여주기 위해 필요한 것은 아래 코드를 사용하는 것입니다.

Scaffold.of(context).showSnackBar(SnackBar(
          content: Text("Sending Message"),
        ));

그러나 스캐 폴드 컨텍스트를 사용해야한다는 것을 기억하십시오.

3 : 네이티브 API 사용.

위의 두 가지 방법이 이미 있으면이 방법은 더 이상 의미가 없습니다. 이 방법을 사용하면 Android 및 iOS 용 기본 코드를 작성한 다음 플러그인으로 변환해야합니다. 이 방법은 시간을 소비하며 바퀴를 재발 명해야합니다. 이미 발명되었습니다.



1

Pubspecs.yaml의 의존성에 flutter_just_toast 추가

의존성 :

flutter_just_toast: ^1.0.1

다음으로 패키지를 클래스로 가져옵니다.

import 'package:flutter_just_toast/flutter_just_toast.dart';

메시지로 토스트 구현

Toast.show( message: "Your toast message", 
    duration: Delay.SHORT, 
    textColor: Colors.black);


1

이를 위해 다른 버전이 있습니다.

1) 우선, Flutter의 위젯 인 SnackBar를 사용할 수 있습니다.

2) pub.dev의 toast, flutter_toast와 같은 라이브러리를 사용할 수 있습니다.

3) 세 번째 버전은 사용자 정의 위젯을 작성 중입니다. 오버레이 위젯과 Flutter의 애니메이션을 사용하여 만들 수 있습니다.

이 학습서에 대해 자세히 알아볼 수 있습니다. 여기 링크가 있습니다




0

1 단계:

의존성 :

flutter_just_toast: ^1.0.1

2 단계:

import 'package:flutter_just_toast/flutter_just_toast.dart';

3 단계 :

Toast.show(
message: "Your toast message",
duration: Delay.SHORT,
textColor: Colors.black);


0

이 의존성을 사용 toast: ^0.1.3 하십시오 : import 'package:toast/toast.dart'; 그런 다음 페이지에서 토스트의 의존성을 가져 오십시오 : 위젯의 onTap () Toast.show("Toast plugin app", context,duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);


0

이 패키지를 사용할 수 있습니다 : 토스트

이 줄을 의존성에 추가하십시오

toast: ^0.1.5

다음과 같이 사용하십시오 :

import 'package:toast/toast.dart';
Toast.show("Toast plugin app", context, duration: Toast.LENGTH_SHORT, gravity:  Toast.BOTTOM);


0

설레다에 토스트를위한 위젯이 없습니다. 이 플러그인 유스 케이스 로 이동할 수 있습니다 :

Fluttertoast.showToast(
msg: "My toast messge",
textColor: Colors.white,
toastLength: Toast.LENGTH_SHORT,
timeInSecForIos: 1,
gravity: ToastGravity.BOTTOM,
backgroundColor: Colors.indigo,);

0

"fluttertoast"라이브러리를 사용할 수 있습니다. 이렇게하려면 pubspec.yaml 파일에 다음을 추가하십시오.

dependencies:
  fluttertoast: ^3.1.0

그런 다음 토스트가 필요한 다트 파일로 해당 라이브러리를 가져와 코드를 작성하십시오. 예를 들어 다음 코드를 참조하십시오.

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());

0

코드 아래 가져 오기cupertino_icons: ^0.1.2쓰기

showToast(BuildContext context, String message) {
 showDialog(
context: context,
builder: (BuildContext context) {
return CupertinoAlertDialog( 
title: Text("Name of App",
          content: Text(message,
          actions: <Widget>[
            FlatButton(
              child: Text("OK"),
              onPressed: () {
                Navigator.of(context).pop();
              },
            )
          ],
        );
      });

0

flutter의 토스트 메시지는 bot_toast 라이브러리를 사용 하십시오 . 이 라이브러리는 기능이 풍부하고 알림, 텍스트,로드, 첨부 파일 등을 표시 할 수 있도록 지원합니다. 토스트

여기에 이미지 설명을 입력하십시오


0

아주 간단합니다

플러터 토스트 패키지를 설치하면됩니다. 다음 문서를 참조하십시오 : https://pub.dev/packages/fluttertoast

설치 탭에서 pubspec.yaml에 붙여 넣은 종속성을 가져 와서 설치하십시오.

그런 다음 패키지를 가져 오십시오.

가져 오기 'package : fluttertoast / fluttertoast.dart';

위의 줄과 비슷합니다.

FlutterToast 클래스를 사용하면 fluttertoast를 사용할 수 있습니다.

넌 끝났어 !!!


-1

Flutter에서 토스트 메시지를 표시하는 것은 매우 쉽습니다.Scaffold.of(context).showSnackBar(SnackBar( content: Text("Toast Text Here"), ));


-2

FlutterToast와 같은 것을 사용할 수 있습니다

lib 가져 오기

fluttertoast: ^2.1.4

아래와 같이 사용

Fluttertoast.showToast(
    msg: "Hello world",
    textColor: Colors.white,
    toastLength: Toast.LENGTH_SHORT,
    timeInSecForIos: 1,
    gravity: ToastGravity.BOTTOM,
    backgroundColor: Colors.indigo,
);

그게 다야 ..

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.