Home > Software design >  Pass parameter to a reusable widget
Pass parameter to a reusable widget

Time:06-16

I'm trying to use a reusable widget, and I would like to send it a parameter from my widget call that would be different for each reuse

    children: 
const [
                      ImageContainer(),
                      ImageContainer(),
                      ImageContainer()
                    ],

I would like to use it here instead of "0.jpg" something like $id.jpg The objective is to get a different photo depending on the widget

class ImageContainer extends StatefulWidget {
  const ImageContainer({Key? key}) : super(key: key);

  @override
  State<ImageContainer> createState() => _ImageContainerState();
}

class _ImageContainerState extends State<ImageContainer> {
  File? image;

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

      if (image == null) return;

      final imageTemp = File(image.path);

      setState(() => this.image = imageTemp);
      final Directory extDir = await getApplicationDocumentsDirectory();
      String dirPath = extDir.path;
      const fileName = '0';
      final File localImage = await imageTemp.copy('$dirPath/$fileName.jpg');
      print(localImage);
    } on PlatformException catch (e) {}
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: () {
          pickImage();
        },
        child: Container(
            decoration: BoxDecoration(
                image: DecorationImage(
                  image: FileImage(File(
                      "/data/user/0/com.example.live_snap/app_flutter/0.jpg")),
                  fit: BoxFit.cover,
                ),
                color: Colors.black87,
                borderRadius: BorderRadius.circular(5)),
            child: Align(
              alignment: FractionalOffset.bottomLeft,
              child: MaterialButton(
                  shape: const RoundedRectangleBorder(
                    borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(5),
                      bottomRight: Radius.circular(5),
                    ),
                  ),
                  materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                  minWidth: double.infinity,
                  color: Colors.yellow,
                  onPressed: () {},
                  child: Text('SNAPPER')),
            )));
  }
}

Thank you so much!

CodePudding user response:

use ListView.builder

final List<String> imageNames = <String>['apple', 'orange', 'banana'];

ListView.builder(
  itemCount: imageNames.length,
  itemBuilder: (BuildContext context, int index) {
    return   ImageContainer(imageName: imageNames[index]),
  }
);

/// and add parameter imageName to your ImageContainer()

class ImageContainer extends StatefulWidget {
  final String imageName
  const ImageContainer({Key? key, required imageName}) : super(key: key);

  @override
  State<ImageContainer> createState() => _ImageContainerState();
}

class _ImageContainerState extends State<ImageContainer> {
 
  /// access the imageName in here

  File? image;

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

      if (image == null) return;

      final imageTemp = File(image.path);

      setState(() => this.image = imageTemp);
      final Directory extDir = await getApplicationDocumentsDirectory();
      String dirPath = extDir.path;
      const fileName = '0';
      final File localImage = await imageTemp.copy('$dirPath/$fileName.jpg');
      print(localImage);
    } on PlatformException catch (e) {}
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: () {
          pickImage();
        },
        child: Container(
            decoration: BoxDecoration(
                image: DecorationImage(
                  image: FileImage(File(
                      "/data/user/0/com.example.live_snap/app_flutter/0.jpg")),
                  fit: BoxFit.cover,
                ),
                color: Colors.black87,
                borderRadius: BorderRadius.circular(5)),
            child: Align(
              alignment: FractionalOffset.bottomLeft,
              child: MaterialButton(
                  shape: const RoundedRectangleBorder(
                    borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(5),
                      bottomRight: Radius.circular(5),
                    ),
                  ),
                  materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                  minWidth: double.infinity,
                  color: Colors.yellow,
                  onPressed: () {},
                  child: Text('SNAPPER')),
            )));
  }
}


CodePudding user response:

I would post a comment but my reputation is not high enough..

It looks like you just need a id var in your stateful widget.

class ImageContainer extends StatefulWidget {
  final String id;
  const ImageContainer({Key? key, required this.id}) : super(key: key);

  @override
  State<ImageContainer> createState() => _ImageContainerState();
}

class _ImageContainerState extends State<ImageContainer> {
  File? image;

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

      if (image == null) return;

      final imageTemp = File(image.path);

      setState(() => this.image = imageTemp);
      final Directory extDir = await getApplicationDocumentsDirectory();
      String dirPath = extDir.path;
      const fileName = '0';
      final File localImage = await imageTemp.copy('$dirPath/$fileName.jpg');
      print(localImage);
    } on PlatformException catch (e) {}
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: () {
          pickImage();
        },
        child: Container(
            decoration: BoxDecoration(
                image: DecorationImage(
                  image: FileImage(File(
                      widget.id ".jpg")),
                  fit: BoxFit.cover,
                ),
                color: Colors.black87,
                borderRadius: BorderRadius.circular(5)),
            child: Align(
              alignment: FractionalOffset.bottomLeft,
              child: MaterialButton(
                  shape: const RoundedRectangleBorder(
                    borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(5),
                      bottomRight: Radius.circular(5),
                    ),
                  ),
                  materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                  minWidth: double.infinity,
                  color: Colors.yellow,
                  onPressed: () {},
                  child: Text('SNAPPER')),
            )));
  }
}

Then you can do

 children: 
const [
      ImageContainer(id:"/data/user/0/com.example.live_snap/app_flutter/0"),
],

Let me know if I did not understand your question correctly!

  • Related