Durga
Durga

Reputation: 11

How to call a method from another class in flutter

I'm Beginner to coding. I have created a Image picker in flutter, I want to use the image picker in many different pages, so I have created a separate class, but when I call the method in other pages, it just open the gallery but,it is not picking the image from gallery and displaying the picked image.There is no any error.

Kindly, help to solve the issue.

Thanks in advance

My Code:

main.dart:

    import 'package:flutter/material.dart';
    import 'package:project1test/healthscreen_expat.dart';
    import 'package:project1test/forms/parkings.dart';

class accomodationform extends StatefulWidget {
  String text;
  accomodationform(String name) {
    text = name;
  }
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return MyAppState(text);
  }
}

class MyAppState extends State<accomodationform> {
  Mod1 mod11 = new Mod1();

  String labels;
  MyAppState([String label]) {
    labels = label;
  }
  Image1 im = Image1();
  final scaffoldkey = new GlobalKey<ScaffoldState>();
  final formkey = new GlobalKey<FormState>();

  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: new Padding(
          padding: EdgeInsets.only(left: 20.0, right: 20.0, top: 20),
          child: new Form(
              key: formkey,
              child: ListView(children: <Widget>[
                mod11.user(),
              ]))),
    );
  }
}

imagepick.dart

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class Mod1 {
  var images1accom;

  user() {
    List<dynamic> img = List();
    return Container(
      margin: EdgeInsets.only(top: 20, right: 20, left: 20),
      padding: EdgeInsets.only(top: 20.0),
      width: double.infinity,
      height: 150.0,
      color: Colors.white70,
      child: Center(
        child: Row(
          //mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            OutlineButton(
                onPressed: () async {
                  images1accom =
                      await ImagePicker.pickImage(source: ImageSource.gallery);

                  img.add(images1accom);
                },
                child: Row(children: <Widget>[
                  Icon(Icons.camera_alt),
                  Text(
                    "Choose File",
                    style: TextStyle(fontSize: 12.0),
                    textAlign: TextAlign.end,
                  )
                ]),
                borderSide: BorderSide(color: Colors.pink),
                textColor: Colors.pinkAccent,
                padding: EdgeInsets.all(10.0),
                shape: new RoundedRectangleBorder(
                  borderRadius: new BorderRadius.circular(10.0),
                )),
            Expanded(
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: img.length,
                itemBuilder: (BuildContext c, int position) {
                  return (Image.file(
                    img[position],
                    fit: BoxFit.cover,
                    repeat: ImageRepeat.noRepeat,
                  ));
                },
              ),
            ),
          ],
        ),
      ),
     );
     }
     }

Upvotes: 1

Views: 2300

Answers (3)

Mohammad_Asef
Mohammad_Asef

Reputation: 336

if you want to use a method in different pages you can use Providers

Upvotes: 0

jonatas Borges
jonatas Borges

Reputation: 2237

Well, I think maybe it would be good for you to study object-oriented programming, dart, and how Flutter works. Initially, I need to tell you that you simply cannot do what you are trying to do, insert widgets within classes, with separate functions, and try to instantiate it within a Stateful.

Widgets must not be instantiated, and if you want to componentize something, you must do it using a stateful or stateless class, not an ordinary class.

Your Mod class should look like this:

class ChoosePic extends StatefulWidget {
  ChoosePic({Key key}) : super(key: key);

  @override
  _ChoosePicState createState() => _ChoosePicState();
}

class _ChoosePicState extends State<ChoosePic> {
  List<dynamic> img = List();
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: 20, right: 20, left: 20),
      padding: EdgeInsets.only(top: 20.0),
      width: double.infinity,
      height: 150.0,
      color: Colors.white70,
      child: Center(
        child: Row(
          //mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            OutlineButton(
                onPressed: () async {
                  File images1accom =
                      await ImagePicker.pickImage(source: ImageSource.gallery);
                  img.add(images1accom);
                  setState(() {});
                },
                child: Row(children: <Widget>[
                  Icon(Icons.camera_alt),
                  Text(
                    "Choose File",
                    style: TextStyle(fontSize: 12.0),
                    textAlign: TextAlign.end,
                  )
                ]),
                borderSide: BorderSide(color: Colors.pink),
                textColor: Colors.pinkAccent,
                padding: EdgeInsets.all(10.0),
                shape: new RoundedRectangleBorder(
                  borderRadius: new BorderRadius.circular(10.0),
                )),
            Expanded(
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: img.length,
                itemBuilder: (BuildContext c, int position) {
                  return (Image.file(
                    img[position],
                    fit: BoxFit.cover,
                    repeat: ImageRepeat.noRepeat,
                  ));
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

And you can to use it with

child: ChoosePic()

I have no idea why you are using a listview in your main class, but if it is really necessary, you would do this:

ListView(children: <Widget>[
                ChoosePic(),
              ])

If you want the value of img, you will need a state manager for this:

Using Get (add this package to pubspec): https://pub.dev/packages/get

Create class with shared state:

class Controller extends GetController {
  static Controller get to => Get.find();

  List<dynamic> img = List();
  takeImage() {
    File images1accom =
        await ImagePicker.pickImage(source: ImageSource.gallery);
    img.add(images1accom);
    update(this);
  }
}
// use it:
class ChoosePic extends StatefulWidget {
  ChoosePic({Key key}) : super(key: key);

  @override
  _ChoosePicState createState() => _ChoosePicState();
}

class _ChoosePicState extends State<ChoosePic> {

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: 20, right: 20, left: 20),
      padding: EdgeInsets.only(top: 20.0),
      width: double.infinity,
      height: 150.0,
      color: Colors.white70,
      child: Center(
        child: Row(
          //mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            OutlineButton(
                onPressed: () async {
                  Controller.to.takeImage();
                },
                child: Row(children: <Widget>[
                  Icon(Icons.camera_alt),
                  Text(
                    "Choose File",
                    style: TextStyle(fontSize: 12.0),
                    textAlign: TextAlign.end,
                  )
                ]),
                borderSide: BorderSide(color: Colors.pink),
                textColor: Colors.pinkAccent,
                padding: EdgeInsets.all(10.0),
                shape: new RoundedRectangleBorder(
                  borderRadius: new BorderRadius.circular(10.0),
                )),
            Expanded(
              child: GetBuilder<Controller>(
                init: Controller(),
                builder: (controller) {
                  return ListView.builder(
                    scrollDirection: Axis.horizontal,
                    itemCount: controller.img.length,
                    itemBuilder: (BuildContext c, int position) {
                      return (Image.file(
                        controller.img[position],
                        fit: BoxFit.cover,
                        repeat: ImageRepeat.noRepeat,
                      ));
                    },
                  );
                }
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Now you can get the image list from anywhere in your code with:

on widget three controller.img;

GetBuilder<Controller>(
                init: Controller(),
                builder: (controller) {

Example:

GetBuilder<Controller>(
                init: Controller(),
                builder: (controller) {
                  return ListView.builder(
                    scrollDirection: Axis.horizontal,
                    itemCount: controller.img.length,
                    itemBuilder: (BuildContext c, int position) {
                      return (Image.file(
                        controller.img[position],
                        fit: BoxFit.cover,
                        repeat: ImageRepeat.noRepeat,
                      ));
                    },
                  );

And take it out of the widget tree with:

Controller.to.img

Note: init: Controller() can only be used once, if you need GetBuilder elsewhere, don't use it. Use, for example:

GetBuilder<Controller>(
                    builder: (controller) {
                      return ListView.builder(
                        scrollDirection: Axis.horizontal,
                        itemCount: controller.img.length,
                        itemBuilder: (BuildContext c, int position) {
                          return (Image.file(
                            controller.img[position],
                            fit: BoxFit.cover,
                            repeat: ImageRepeat.noRepeat,
                          ));
                        },
                      );

Well, I shouldn't answer that, as it qualifies as a general question, but since you are a beginner, I answered to help you, in detail. I hope you understand the basics soon, and become a great developer someday. Welcome to Flutter!

Upvotes: 1

Kinjal
Kinjal

Reputation: 456

You need to create a separate widget for Mod1 class.

MyAppState

Widget build(BuildContext context) {
    return Scaffold(
      body: new Padding(
          padding: EdgeInsets.only(left: 20.0, right: 20.0, top: 20),
          child: new Form(key: formkey, child: Mod1())),
    );
  }

Mod1 widget

class Mod1 extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => Mod1State();
}

class Mod1State extends State<Mod1> {
  var images1accom;
  List<dynamic> img = List();

  @override
  Widget build(BuildContext context) {

    return Container(
      margin: EdgeInsets.only(top: 20, right: 20, left: 20),
      padding: EdgeInsets.only(top: 20.0),
      width: double.infinity,
      height: 150.0,
      color: Colors.white70,
      child: Center(
        child: Row(
          //mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            OutlineButton(
                onPressed: () async {
                  images1accom =
                      await ImagePicker.pickImage(source: ImageSource.gallery);
                  setState(() {
                    img.add(images1accom);
                  });

                },
                child: Row(children: <Widget>[
                  Icon(Icons.camera_alt),
                  Text(
                    "Choose File",
                    style: TextStyle(fontSize: 12.0),
                    textAlign: TextAlign.end,
                  )
                ]),
                borderSide: BorderSide(color: Colors.pink),
                textColor: Colors.pinkAccent,
                padding: EdgeInsets.all(10.0),
                shape: new RoundedRectangleBorder(
                  borderRadius: new BorderRadius.circular(10.0),
                )),
            Expanded(
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: img.length,
                itemBuilder: (BuildContext c, int position) {
                  return (Image.file(
                    img[position],
                    fit: BoxFit.cover,
                    repeat: ImageRepeat.noRepeat,
                  ));
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Upvotes: 0

Related Questions