call method in one stateful widget from another stateful widget - Flutter

后端 未结 7 975
耶瑟儿~
耶瑟儿~ 2020-11-29 17:59

I have a flutter project that i am working on i cant put the whole code cause its more than 500 lines of code so i will try to ask my question as simply as i acn using the i

7条回答
  •  难免孤独
    2020-11-29 18:28

    I just found a simplest solution for this question

    Appearently, You can just create a file that contain only a method and you will be able to call it directly

    For Example, I want to create a showModalBottomSheet method in file named custom_show_bottom_sheet.dart :

    import 'package:flutter/material.dart';
    
    customShowBottomSheet(context, Widget child){
        showModalBottomSheet(
          isScrollControlled: true,
          context: context,
          builder: (BuildContext context) {
            return Wrap(
              children: [
                child,
              ],
            );
          });
    }
    

    And you can simply call it like this:

    import 'package:flutter/material.dart';
    import '../custom_show_bottom_sheet.dart';
    
    class TestScreen extends StatelessWidget {
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: FloatingActionButton(
                onPressed: (){
                  customShowBottomSheet( //A method is called here
                      context,
                      Container(
                        height: 200,
                        child: Text("This is a test"),
                      )
                  );
                }),
          ),
        );
      }
    }
    

    Hope this be a help! Please let me know if I misunderstand your question or anything.

提交回复
热议问题