flutterflutter-showmodalbottomsheet

Flutter showModalBottomSheet in diferrent class


Let's say I have a text and button in main screen(class) and showModalBottomSheet in different class, when main screen button pressed, it will trigger showModalBottomSheet that contain a button, that button will dismissed the modal bottom sheet and change(updateUI) text in main screen.

Can you give example how I can achieve this? or showModalBottomSheet cannot use in different class when I want to update the UI?


Solution

  • You can try this code i hope this is a use-full

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: MainScreen(),
        );
      }
    }
    
    class MainScreen extends StatefulWidget {
      @override
      _MainScreenState createState() => _MainScreenState();
    }
    
    class _MainScreenState extends State<MainScreen> {
      String _displayText = 'Initial Text';
    
      void _updateText(String newText) {
        setState(() {
          _displayText = newText;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Main Screen'),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(_displayText),
                MaterialButton(
                  onPressed: () {
                    showModalBottomSheet(
                      context: context,
                      builder: (BuildContext context) {
                        return BottomSheetWidget(updateText: _updateText);
                      },
                    );
                  },
                  child: Text('Show Modal Bottom Sheet'),
                ),
              ],
            ),
          ),
        );
      }
    }
    
    class BottomSheetWidget extends StatelessWidget {
      final Function(String) updateText;
    
      BottomSheetWidget({required this.updateText});
    
      @override
      Widget build(BuildContext context) {
        return Container(
          child: Padding(
            padding: EdgeInsets.all(16.0),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
                MaterialButton(
                  onPressed: () {
                    updateText('Updated Text');
                    Navigator.pop(context);
                  },
                  child: Text('Update Text and Close'),
                ),
              ],
            ),
          ),
        );
      }
    }