Home > Back-end >  import file and cant Access to its var and functions in another one
import file and cant Access to its var and functions in another one

Time:10-11

hello folks i have 2 dart file and i iwant use file? image thats wrote in file offerform.dart and import it on Page2.dart but i cant get access to it can you tell me please what the problem on my code ? and thank you so much

offerForm.dart

import 'package:firebase_auth/offersP.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
//import 'offersdetailsP.dart';
import 'package:image_picker/image_picker.dart';


class offerform extends StatelessWidget {
  const offerform({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('إنشاء عرض جديد'),
      ),
      body: const Center(
        child: MyStatefulWidget(),
      ),
    );

  }
}

//enum offer_type { land,house,apartment }
//enum offer_method { sell,rent }




class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({super.key});

  @override
  State<MyStatefulWidget> createState() => MyStatefulWidgetState();
}

class MyStatefulWidgetState extends State<MyStatefulWidget> {
  String? offer_type;
  String? offer_method;
  final imageUrl = TextEditingController();

  String sell = 'بيع';
  String rent = 'اجار';
  String land = 'ارض';
  String house = 'فلة';
  String apartment = 'شقة';

  File? image;

  Future uploadImage() async{
    try {
      final image = await ImagePicker().pickImage(source: ImageSource.gallery);

      if(image == null) return;

      final imageTemp = File(image.path);

      setState(() => this.image = imageTemp ) ;
      } on PlatformException catch(e) {
      print('faild to upload $e');
      }
    }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Padding(padding: EdgeInsets.all(8.0)),
        Text('النوع', style: TextStyle(
            fontSize: 18
        ),),
        Divider(),
        ListTile(
          title: const Text('أرض'),
          leading: Radio(
            value: 'أرض',
            groupValue: offer_type,
            onChanged: (value) {
              setState(() {
                offer_type = value;
              });
            },
          ),
        ),
        ListTile(
          title: const Text('فلة'),
          leading: Radio(
            value: 'فلة',
            groupValue: offer_type,
            onChanged: (value) {
              setState(() {
                offer_type = value;
              });
            },
          ),
        ),
        ListTile(
          title: const Text('شقة'),
          leading: Radio(
            value: 'شقة',
            groupValue: offer_type,
            onChanged: (value) {
              setState(() {
                offer_type = value;
              });
            },
          ),
        ),
          Column(
          children: <Widget>[
            Text('التصنيف', style: TextStyle(
                fontSize: 18
            ),),
            Divider(),
          ListTile(
          title: const Text('للبيع'),
          leading : Radio(
            value: 'للبيع',
            groupValue: offer_method,
            onChanged: (value) {
              setState(() {
                offer_method = value;
              });
              },
            ),
          ),
          ListTile(
          title: const Text('للإجار'),
          leading: Radio(
            value: 'للإجار',
            groupValue: offer_method,
            onChanged: (value) {
              setState(() {
                offer_method = value;
              });
             },
            ),
          ),
            IconButton(
              onPressed: uploadImage,
              icon: Icon(Icons.add),
            ),
            ElevatedButton(
              onPressed: () {
                offers_list.add(Offers(title: offer_type!  ' '  offer_method! , describtion: "describtion", price: 190,image:imageUrl.text, availability: true, location: "location"));
                print(offer_type!  offer_method!);
                print(imageUrl);
              }, child: null,
            ),
      ],

        )
      ],

    );

  }
} 

and this my second file which i try to import the first file on it

Page2.dart

import 'package:flutter/material.dart';
import 'offersP.dart';
//import 'offerForm.dart';



class offersPage extends StatelessWidget {
    const offersPage({super.key});
    @override
    Widget build(BuildContext context) {
      return Center(
        child: ListView.builder(itemCount : offers_list.length ,
          itemBuilder: (context, index){
          Offers offer = offers_list[index];
          return Card(
              child : Column (
                  children: <Widget>[
              ListTile(
                title: Text(offer.title.toString()),
                subtitle: Text(offer.describtion.toString()),
                leading: Image.network(),
                onTap: (){
                  Navigator.push(context,
                      MaterialPageRoute(
                          builder: (context) => offersdetail(offer)));
                },
              ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
            children: [
                Icon(Icons.price_check),
                Text(offer.price.toString()),
                SizedBox(
                  width: 150.0,
                ),
                Icon(Icons.location_on),
                Text(offer.location.toString())
                ],
            )
            ]),
          );
        }),
      );
    }
} ```

CodePudding user response:

does it work if you try this?

import offerform.dart as offerform

and on the page use the image using:

offerform.image

CodePudding user response:

The reason that you can't access it directly is that its inside the class and you must first create an instance of that class and then be able to access it

But in this case this isn't very fun way to do it. You should use state management to have a shared variable and method and be able to update your UI accordingly

Also you can use a static class to put your image and the method that downloads it inside it but then you don't have the option to update your UI

CodePudding user response:

You can use it same this:

up class :

typedef void PathSelected(File? file);

but maybe not work for your case because there is no related class offersPage with MyStatefulWidget

and i think this idea for code is better, try this code now:

class test{
   static SharedPreferences? prefs;
  Future<File?> uploadImage() async{
    try {
      final image = await ImagePicker().pickImage(source: ImageSource.gallery);

      if(image == null) return;

      setPath(image.path);
      return File(image.path);
      } on PlatformException catch(e) {
      print('faild to upload $e');
      }
    }
  static Future<void> setPath(String? path) async {
    prefs = await SharedPreferences.getInstance();
       return prefs!.setString('path', path);

  }
  static Future<String?> getPath() async{
    prefs = await SharedPreferences.getInstance();
    return prefs!.getString('path');
  }

}

and set function File(await test.getPath()) in class offersPage

  • Related