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

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



답변

다음을 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),
      ),
    );
  }
}


답변

플러그인 사용

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

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


답변

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),
          );
        }
      ),
    );
  }
}

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


답변

토스트 메시지를 표시하려면 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');

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


답변

설레임 : ^ 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
    );


답변

패키지 플러시 바를 사용하는 대체 솔루션을 제공하고 싶습니다.
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);


답변

lib 가져 오기

설레다 : 3.1.3

아래와 같이 사용

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

);