ponnamkarthik/FlutterToast

UnsupportedOperationException When Using Fluttertoast

Opened this issue · 0 comments

Issue: UnsupportedOperationException When Using Fluttertoast

Description

I am encountering a java.lang.UnsupportedOperationException when trying to display a toast message using Fluttertoast.showToast. The issue occurs even when using the example code provided in the Fluttertoast.

Steps to Reproduce

  1. Create a new Flutter project.

  2. Add fluttertoast as a dependency in pubspec.yaml.

  3. Use the example code from the Fluttertoast GitHub README:

    import 'package:flutter/material.dart';
    import 'package:fluttertoast/fluttertoast.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: MyHomePage(),
        );
      }
    }
    
    class MyHomePage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text("Home"),
          ),
          body: Center(
            child: ElevatedButton(
              onPressed: () {
                Fluttertoast.showToast(
                  msg: "This is a Toast message",
                  toastLength: Toast.LENGTH_SHORT,
                  gravity: ToastGravity.CENTER,
                  timeInSecForIosWeb: 1,
                  backgroundColor: Colors.red,
                  textColor: Colors.white,
                  fontSize: 16.0
                );
              },
              child: Text("Show Toast"),
            ),
          ),
        );
      }
    }
  4. Run the app on an Android device or emulator.

  5. Press the "Show Toast" button.

Expected Behavior

The toast message should be displayed at the center of the screen without any errors.

Actual Behavior

The app crashes with the following error in the logcat:

E/AndroidRuntime(23822): java.lang.UnsupportedOperationException: Tried to obtain display from a Context not associated with one. Only visual Contexts (such as Activity or one created with Context#createWindowContext) or ones created with Context#createDisplayContext are associated with displays. Other types of Contexts are typically related to background entities and may return an arbitrary display.

Additional Information

  • Flutter Version: 3.22
  • Fluttertoast Version: 8.2.6

Possible Workarounds Tried

  1. Ensuring navigatorKey is properly initialized and used.
  2. Checking for null context before calling Fluttertoast.showToast.
  3. Using a direct BuildContext from within a widget.

None of these workarounds resolved the issue.

Additional Context

This issue appears to be related to the type of Context that is being used when Fluttertoast.showToast is called. It seems like the context might not be a visual context, causing the UnsupportedOperationException.