Search code examples
flutterdartoopwebapi

how to put create new object before put input in Flutter


i have this kind of prob, i want integrate Flutter with .Net core web API. im new to flutter so, i just followed the tutorial but the error here where object is required to initialized first this is my snippet , i dont know what to put in (edit:false, service:null)

floatingActionButton: FloatingActionButton(
          onPressed: () => Navigator.of(context).pushNamed(
            AddUpdateService.routeName,
            arguments: ServiceArgument(edit: false, service: null),
          ),
          child: const Icon(Icons.add),
        ),

service here is an object i want to add or update in AddUpdateService, below is the code of AddUpdateService

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

import '../bloc/bloc.dart';
import '../model/models.dart';
import 'ScreenRoute.dart';
import 'ServiceMainScreen.dart';


class AddUpdateService extends StatefulWidget {
  static const routeName = 'courseAddUpdate';
  final ServiceArgument args;

  const AddUpdateService({super.key, required this.args});
  @override
  _AddUpdateServiceState createState() => _AddUpdateServiceState();
}

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

  final Map<String, dynamic> _service = {};

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.args.edit ? "Edit Course" : "Add New Course"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Form(
          key: _formKey,
          child: Column(
            children: [

              TextFormField(
                  initialValue: widget.args.edit ? widget.args.service.ServiceName : '',
                  validator: (value) {
                    if (value!.isEmpty) {
                      return 'Please enter course code';
                    }
                    return null;
                  },
                  decoration: const InputDecoration(labelText: 'Service Name'),
                  onSaved: (value) {
                    setState(() {
                      _service["serviceName"] = value;
                    });
                  }),
              TextFormField(
                  initialValue:
                  widget.args.edit ? widget.args.service.Description : '',
                  validator: (value) {
                    if (value!.isEmpty) {
                      return 'Please enter service  Description';
                    }
                    return null;
                  },
                  decoration: const InputDecoration(labelText: 'Description'),
                  onSaved: (value) {
                    _service["description"] = value;
                  }),
              TextFormField(
                  initialValue: widget.args.edit
                      ? widget.args.service.Category
                      : '',
                  validator: (value) {
                    if (value!.isEmpty) {
                      return 'Please enter Service Category';
                    }
                    return null;
                  },
                  decoration: const InputDecoration(labelText: 'Category'),
                  onSaved: (value) {
                    setState(() {
                      _service["category"] = value;
                    });
                  }),

              TextFormField(
                  initialValue: widget.args.edit
                      ? widget.args.service.InitialPrice.toString()
                      : '',
                  validator: (value) {
                    if (value!.isEmpty) {
                      return 'Please enter Service Initial Pice';
                    }
                    return null;
                  },
                  decoration: const InputDecoration(labelText: 'InitialPrice'),
                  onSaved: (value) {
                    setState(() {
                      _service["initialPrice"] = int.parse(value!);
                    });
                  }),
              TextFormField(
                  initialValue: widget.args.edit
                      ? widget.args.service.IntermediatePrice.toString()
                      : '',
                  validator: (value) {
                    if (value!.isEmpty) {
                      return 'Please enter Service Intermediate Pice';
                    }
                    return null;
                  },
                  decoration: const InputDecoration(labelText: 'Intermediate'),
                  onSaved: (value) {
                    setState(() {
                      _service["intermediatePrice"] = int.parse(value!);
                    });
                  }),
            TextFormField(
                initialValue: widget.args.edit
                    ? widget.args.service.AdvancedPrice.toString()
                    : '',
                validator: (value) {
                  if (value!.isEmpty) {
                    return 'Please enter Service Advanced Pice';
                  }
                  return null;
                },
                decoration: const InputDecoration(labelText: 'AdvancedPrice'),
                onSaved: (value) {
                  setState(() {
                    _service["advancedPrice"] = int.parse(value!);
                  });
                }),
              Padding(
                padding: const EdgeInsets.symmetric(vertical: 16.0),
                child: ElevatedButton.icon(
                  onPressed: () {
                    final form = _formKey.currentState;
                    if (form!.validate()) {
                      form.save();
                      final ServiceEvent event = widget.args.edit
                          ? ServiceUpdate(

                        Service(
                          id: widget.args.service.id,
                         ServiceName: _service["serviceName"],
                        Description: _service["description"],
                        Category: _service["category"],
                        InitialPrice: _service["initialPrice"],
                        IntermediatePrice: _service["intermediatePrice"],
                        AdvancedPrice: _service["advancedPrice"], imageUrl: '',
                        ),
                      )
                          : ServiceCreate(
                        Service(

                          ServiceName: _service["serviceName"],
                          Description: _service["description"],
                          Category: _service["category"],
                          InitialPrice: _service["initialPrice"],
                          IntermediatePrice: _service["intermediatePrice"],
                          AdvancedPrice: _service["advancedPrice"], id: 123, imageUrl: '',
                        ),
                      );
                      BlocProvider.of<ServiceBloc>(context).add(event);
                      Navigator.of(context).pushNamedAndRemoveUntil(
                          ServiceMainScreen.routeName, (route) => false);
                    }
                  },
                  label: const Text('SAVE'),
                  icon: const Icon(Icons.save),
                ),
              ),

            ],
          ),
        ),
      ),
    );
  }
}

how to put initial object as null before putting inputs in next page(AddUpdateService), below is the argument class

class ServiceArgument {
  final Service service;
  final bool edit;
  ServiceArgument({required this.edit, required this.service});
}

how to solve this


Solution

  • Flutter is null-safe, which means that by default variables can't be null unless you specify it as nullable. You can do this by adding a ? behind the type. So change

    class ServiceArgument {
      final Service service;
      final bool edit;
      ServiceArgument({required this.edit, required this.service});
    }
    

    to

    class ServiceArgument {
      final Service? service;
      final bool edit;
      ServiceArgument({required this.edit, required this.service});
    }
    

    if you want to allow putting null into service