Home > Blockchain >  create field for load images
create field for load images

Time:03-14

I have a code that outputs fields for the user to fill in (code below. I have shortened it here for ease of reading.). I would like to add one more field to this form, which can upload various photos from the phone gallery (preferably with the ability to delete a photo if the user made a mistake when choosing). How can I implement this?

class FormForDeviceService extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _FormForDeviceService();
}

class _FormForDeviceService extends State {
  final _formKey = GlobalKey<FormState>();

  Widget build(BuildContext context) {
    return Container(padding: const EdgeInsets.all(10.0),
        child: Form(key: _formKey, child: Column(children: <Widget>[

          new Text('What is problem', style: TextStyle(fontSize: 20.0),),
          new TextFormField(decoration: const InputDecoration(
            hintText: 'Describe the problem',),
              
          ElevatedButton(
            onPressed: (){if(_formKey.currentState!.validate()) {_formKey.currentState?.reset();
            ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('Form completed successfully', style: TextStyle(color: Colors.black),),
                  backgroundColor: Colors.yellow,));
            }},
            child: const Text('Submit', style: TextStyle(color: Colors.black),),
            style: ButtonStyle(backgroundColor: MaterialStateProperty.all(Colors.yellow)),)
        ],)));
  }
}

Page at the moment enter image description here

my expectations (or something similar) enter image description here

CodePudding user response:

An another approach is here- (I have made a separate widget to handle all these things and you just need to attach it in any scrollable widget) my code is as follow:

Main Code with that custom widget:

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_memory/image_picker_widget.dart';

void main() {
  runApp(GetMaterialApp(title: 'Flutter', home: Flutter()));
}

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

  @override
  State<Flutter> createState() => _FlutterState();
}

class _FlutterState extends State<Flutter> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter'),
        centerTitle: true,
      ),
      body: Center(
        child: Column(
          children: [
            //This is the widget I am talking about
            ImagePickerWidget()
          ],
        ),
      ),
    );
  }
}

And now the code for that custom widget:

import 'dart:typed_data';

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

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

  @override
  State<ImagePickerWidget> createState() => _ImagePickerWidgetState();
}

class _ImagePickerWidgetState extends State<ImagePickerWidget> {
  late List<CustomImage> images;
  late double size;
  late ImagePicker imagePicker;
  late int idGenerator;

  @override
  void initState() {
    images = [];
    size = 100;
    idGenerator = 0;
    imagePicker = ImagePicker();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        ElevatedButton(
            onPressed: () {
              pickImage();
            },
            child: Text('Pick Image')),
        Wrap(
            children: images.map((image) {
          return Stack(children: [
            SizedBox(
                height: size,
                width: size,
                child: ClipRRect(
                    child: Image.memory(
                  image.imageData,
                  fit: BoxFit.fill,
                ))),
            Positioned(
                right: 4,
                top: 4,
                child: InkWell(
                    onTap: () {
                      //delete image
                      images.removeWhere(
                          (element) => element.imageData == image.imageData);
                      setState(() {});
                    },
                    child: Container(
                        color: Colors.white, child: Icon(Icons.clear))))
          ]);
        }).toList())
      ],
    );
  }

  Future<void> pickImage() async {
    // XFile? image = await imagePicker.pickImage(source: ImageSource.camera);
    XFile? image = await imagePicker.pickImage(source: ImageSource.gallery);
    if (image != null) {
      Uint8List imageData = await image.readAsBytes();
      int id = idGenerator  ;
      images.add(CustomImage(imageData: imageData, id: id));
      setState(() {});
    }
  }
}

class CustomImage {
  Uint8List imageData;
  int id;

  CustomImage({required this.imageData, required this.id});
}

You can customize the widget in order to use the images list of that widget or you can simply pass the callbacks for that.

CodePudding user response:

enter image description here

we store file here your can use path(string) instead file

List<File> myfile = [];

image_picker package used here to pick image

  image_picker: ^0.8.4 10

call like this in your code

        Container(
            height: 200,
            padding: EdgeInsets.all(4),
            child: PickPhoto())

Pick photo widget

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

  @override
  State<PickPhoto> createState() => _PickPhotoState();
}

class _PickPhotoState extends State<PickPhoto> {
  @override
  Widget build(BuildContext context) {
    return Material(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            child: Container(
                width: 45,
                height: 45,
                child: ElevatedButton(
                    onPressed: () async {
                      var file =
                          await picker?.pickImage(source: ImageSource.gallery);

                      setState(() {
                        myfile.add(File(file!.path));
                      });
                    },
                    child: Text("Add Photo"))),
          ),
          Expanded(
            child: ListView.builder(
                // physics: NeverScrollableScrollPhysics(),
                scrollDirection: Axis.horizontal,
                itemCount: myfile.length,
                itemBuilder: (context, index) => Container(
                      padding: EdgeInsets.all(4),
                      height: 175,
                      width: 125,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [
                          Align(
                            alignment: Alignment.topRight,
                            child: IconButton(
                              onPressed: () {
                                setState(() {
                                  myfile.removeAt(index);
                                });
                              },
                              icon: Icon(Icons.close),
                            ),
                          ),
                          Expanded(
                            child: Container(
                              child: myfile[index] == null
                                  ? Text("")
                                  : Image.file(
                                      myfile[index],
                                      fit: BoxFit.fill,
                                    ),
                            ),
                          ),
                        ],
                      ),
                    )),
          )
        ],
      ),
    );
  }
}

SampleCode

import 'dart:io';

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

ImagePicker? picker;

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  picker = ImagePicker();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'MySQL Test',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        children: [FormForDeviceService()],
      ),
    );
  }
}

List<File> myfile = [];
List<int> f = [1, 2, 3, 4, 5];
List<bool> fs = [false, false, false, true, true];

class FormForDeviceService extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _FormForDeviceService();
}

class _FormForDeviceService extends State {
  final _formKey = GlobalKey<FormState>();

  Widget build(BuildContext context) {
    return Container(
        padding: const EdgeInsets.all(10.0),
        child: Form(
            key: _formKey,
            child: Column(
              children: <Widget>[
                new Text(
                  'What is problem',
                  style: TextStyle(fontSize: 20.0),
                ),
                new TextFormField(
                  decoration: const InputDecoration(
                    hintText: 'Describe the problem',
                  ),
                ),
                Container(
                    height: 200,
                    padding: EdgeInsets.all(4),
                    child: PickPhoto()),
                ElevatedButton(
                  onPressed: () {
                    if (_formKey.currentState!.validate()) {
                      _formKey.currentState?.reset();
                      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
                        content: Text(
                          'Form completed successfully',
                          style: TextStyle(color: Colors.black),
                        ),
                        backgroundColor: Colors.yellow,
                      ));
                    }
                  },
                  child: const Text(
                    'Submit',
                    style: TextStyle(color: Colors.black),
                  ),
                  style: ButtonStyle(
                      backgroundColor:
                          MaterialStateProperty.all(Colors.yellow)),
                )
              ],
            )));
  }
}

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

  @override
  State<PickPhoto> createState() => _PickPhotoState();
}

class _PickPhotoState extends State<PickPhoto> {
  @override
  Widget build(BuildContext context) {
    return Material(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            child: Container(
                width: 45,
                height: 45,
                child: ElevatedButton(
                    onPressed: () async {
                      var file =
                          await picker?.pickImage(source: ImageSource.gallery);

                      setState(() {
                        myfile.add(File(file!.path));
                      });
                    },
                    child: Text("Add Photo"))),
          ),
          Expanded(
            child: ListView.builder(
                // physics: NeverScrollableScrollPhysics(),
                scrollDirection: Axis.horizontal,
                itemCount: myfile.length,
                itemBuilder: (context, index) => Container(
                      padding: EdgeInsets.all(4),
                      height: 175,
                      width: 125,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [
                          Align(
                            alignment: Alignment.topRight,
                            child: IconButton(
                              onPressed: () {
                                setState(() {
                                  myfile.removeAt(index);
                                });
                              },
                              icon: Icon(Icons.close),
                            ),
                          ),
                          Expanded(
                            child: Container(
                              child: myfile[index] == null
                                  ? Text("")
                                  : Image.file(
                                      myfile[index],
                                      fit: BoxFit.fill,
                                    ),
                            ),
                          ),
                        ],
                      ),
                    )),
          )
        ],
      ),
    );
  }
}
  • Related