flutter api image parameter showing null

0

hello i am new to flutter and i m using update profile api in my profile api i describe all parameter and image base 64 also now what is going on ! suppose alredy is image showing on my profile pic and i never pic image from my camera and device My "Profile Pic" parameter showing null when i call it...! and when i picke image from my device it showing base 64...! what i want is if there is alredy image showing then profile api function i want success because there is alredy image shown ... now u suggest me when i call Profile api function on my Button wht i need to pass

PickedFile _imageFile;
final ImagePicker _picker = ImagePicker();
String img64;

void takePhoto(ImageSource source) async {
final pickedFile = await _picker.getImage(source: source);
setState(() {
  _imageFile = pickedFile;
  final bytes = Io.File(_imageFile.path).readAsBytesSync();
  img64 = base64Encode(bytes);
  print(img64.substring(0, 100));
 });
}

 Profile(String FirstnName,String Lastname,String Email,String DOB,String 
Anniversary) async {
sharedPreferences = await SharedPreferences.getInstance();
ValidateCustomer();
Map data =
{
  "AccessToken": sharedPreferences.getString("AccessToken"),
  "CustomerId":  sharedPreferences.getInt("CustomerId"),
  "FirstName": FirstnName ,
  "LastName": Lastname,
  "Email": Email,
  "DOB":DOB,
  "AnniversaryDate": Anniversary,
  "ProfilePicture" : img64
};
print(data);
final http.Response response = await http.post(
  Constants.CUSTUMER_WEBSERVICE_UPDATEPROF_URL,
  headers: <String, String>{
    'Content-Type': 'application/json; charset=UTF-8',
  },
  body: jsonEncode(data),
);
var jsonResponse;
if (response.statusCode == 200)
{
  print(sharedPreferences.setString("FirstName", FirstnName));
  jsonResponse = json.decode(response.body);
  sharedPreferences = await SharedPreferences.getInstance();
  sharedPreferences.setString("FirstName", FirstnName);
  sharedPreferences.setString("ProfilePicture",img64);
  print("Response status : ${response.statusCode}");
  print("Response status : ${response.body}");
  print(sharedPreferences);
  if(jsonResponse != null && ! jsonResponse.containsKey("Error")){
    setState(() {
      _isLoading = false;
    });
    print(sharedPreferences);

    Navigator.of(context).push(
        MaterialPageRoute(builder: (context)=>
            ShelfScreen())
    );

  }
  else{
    setState(() {
      _isLoading = false;
    });
    print("Response status : ${response.body}");
  }
}
if (response.statusCode == 404){
  print("Response status : ${response.statusCode}");
  print("Response status : ${response.body}");
}

}

Future<UserUpdate>ProfileUpadte() async {
sharedPreferences = await SharedPreferences.getInstance();
ValidateCustomer();
Map data =
{
  "AccessToken": sharedPreferences.getString("AccessToken"),
  "CustomerId":  sharedPreferences.getInt("CustomerId"),
};
print(data);
final http.Response response = await http.post(
  "http://api.pgapp.in/v1/userdetails",
  headers: <String, String>{
    'Content-Type': 'application/json; charset=UTF-8',
  },
  body: jsonEncode(data),
);
if (response.statusCode == 200)
{
  print("Response status : ${response.statusCode}");
  print("Response status : ${response.body}");

  var jsonResponse = json.decode(response.body);
  if(jsonResponse != null && ! jsonResponse.containsKey("Error")){
    sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.setString("ProfilePicture", 
  jsonResponse["ProfilePicture"]);
    sharedPreferences.setString("FirstName", jsonResponse["FirstName"]);
    print(sharedPreferences);
  }
  else{
    setState(() {
      _isLoading = false;
    });
    print("Response status : ${response.body}");
  }

  return UserUpdate.fromJson(json.decode(response.body));

 }
else {
  // If the server did not return a 201 CREATED response,
  // then throw an exception.
  throw Exception('Failed to load data');
 }
 }

void nextField ({String value,FocusNode focusNode}){
if (value.isNotEmpty){
  focusNode.requestFocus();
}
}

AnimationController _controller;
Animation _animation;

FocusNode _focusNode1 = FocusNode();

bool  _isLoading = false;
String _Firstnm;
String _Lastnm;
String _Mobno;
String _Email;
 String _Dob;
String _Anniversary;
DateTime _selectedDate;
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

 FocusNode Firstname;
 FocusNode LastndName;
 FocusNode Email;
 FocusNode DOB;
 FocusNode Anniversary;
 Future<UserUpdate> _futureProfileupdate;

 @override
 void initState() {
// TODO: implement initState
 super.initState();
 Firstname = FocusNode();
 LastndName = FocusNode();
  Email = FocusNode();
 DOB = FocusNode();
  Anniversary = FocusNode();
 _futureProfileupdate = ProfileUpadte();

 }

 void _showPicker(context) {
  showModalBottomSheet(
    context: context,
    builder: (BuildContext bc) {
      return SafeArea(
        child: Container(
          child: new Wrap(
            children: <Widget>[
              new ListTile(
                  leading: new Icon(Icons.photo_library),
                  title: new Text('Photo Library'),
                  onTap: () {
                    takePhoto(ImageSource.gallery);
                    Navigator.of(context).pop();
                  }),
              new ListTile(
                leading: new Icon(Icons.photo_camera),
                title: new Text('Camera'),
                onTap: () {
                  takePhoto(ImageSource.camera);
                  Navigator.of(context).pop();
                },
              ),
            ],
          ),
        ),
      );
     }
    );
    }

 @override
  Widget build(BuildContext context) {
  return Scaffold(
     resizeToAvoidBottomInset: false,
    resizeToAvoidBottomPadding: false,
    body: (_isLoading) ? Center(child: CircularProgressIndicator()) : 
    FutureBuilder<UserUpdate>(
        future: _futureProfileupdate,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            TextEditingController _textEditingControllerFirstNamee = 
 TextEditingController(text: snapshot.data.firstName);
            TextEditingController _textEditingControllerLastnamee = TextEditingController(text: snapshot.data.lastName);
            TextEditingController _textEditingControllerEmaill = TextEditingController(text: snapshot.data.email);
            TextEditingController _textEditingControllerDOBb = TextEditingController(text: snapshot.data.dob);
            TextEditingController _textEditingControllerAnniversaryy = TextEditingController(text: snapshot.data.anniversaryDate);
            _selectDate(BuildContext context) async {
              DateTime newSelectedDate = await showDatePicker(
                  context: context,
                  initialDate: _selectedDate != null ? _selectedDate : DateTime.now(),
                  firstDate: DateTime(1920),
                  lastDate: DateTime(2040),
                  builder: (BuildContext context, Widget child) {
                    return Theme(
                      data: ThemeData.dark().copyWith(
                        colorScheme: ColorScheme.dark(
                          primary: Colors.deepPurple,
                          onPrimary: Colors.white,
                          surface: Colors.blueGrey,
                          onSurface: Colors.yellow,
                        ),
                        dialogBackgroundColor: Colors.blue[500],
                      ),
                      child: child,
                    );
                  });
              if (newSelectedDate != null) {
                _selectedDate = newSelectedDate;
                _textEditingControllerDOBb
                  ..text = DateFormat.yMMMd().format(_selectedDate)
                  ..selection = TextSelection.fromPosition(TextPosition(
                      offset: _textEditingControllerDOBb.text.length,
                      affinity: TextAffinity.upstream));
              }
            }
            _selectDate2(BuildContext context) async {
              DateTime newSelectedDate = await showDatePicker(
                  context: context,
                  initialDate: _selectedDate != null ? _selectedDate : DateTime.now(),
                  firstDate: DateTime(1920),
                  lastDate: DateTime(2040),
                  builder: (BuildContext context, Widget child) {
                    return Theme(
                      data: ThemeData.dark().copyWith(
                        colorScheme: ColorScheme.dark(
                          primary: Colors.deepPurple,
                          onPrimary: Colors.white,
                          surface: Colors.blueGrey,
                          onSurface: Colors.yellow,
                        ),
                        dialogBackgroundColor: Colors.blue[500],
                      ),
                      child: child,
                    );
                  });

              if (newSelectedDate != null) {
                _selectedDate = newSelectedDate;
                _textEditingControllerAnniversaryy
                  ..text = DateFormat.yMMMd().format(_selectedDate)
                  ..selection = TextSelection.fromPosition(TextPosition(
                      offset: _textEditingControllerAnniversaryy.text.length,
                      affinity: TextAffinity.upstream));
              }
            }


            return Form(
              key: _formKey,
              child: Stack(
                children: <Widget>[
                  Positioned(
                      left: 20,
                      top: 40,
                      child: Center(
                        child: Image.asset(
                          'assets/images/logo.png', height: 50, width: 50,),
                      )
                  ),
                  Positioned(
                      left: 60,
                      right: 60,
                      top: 40,
                      child: Center(
                        child: Image.asset(
                          'assets/images/Textimage.png', height: 50,
                          width: 170,),
                      )
                  ),
                  Positioned(
                      right: 20,
                      top: 40,
                      child: Center(
                          child: IconButton(
                            icon: Icon(Icons.exit_to_app, size: 30,
                              color: Color(0xfff58634),),
                            onPressed: () async {
                        showAboutDialog(context);
                            },
                          )
                      )
                  ),
                  Positioned(
                      left: 70,
                      right: 70,
                      top: 110,
                      child: Center(
                          child: CircleAvatar(
                            backgroundImage: _imageFile == null ? NetworkImage(
                                snapshot.data.profilePicture) : FileImage(Io.File(_imageFile.path)),
                            backgroundColor: Colors.grey,
                            maxRadius: 50,
                          )
                      )
                  ),
                  Positioned(
                    left: 100,
                    right: 70,
                    top: 170,
                    child: InkWell(
                      onTap: (){
                        _showPicker(context);
                      },
                      child: Icon(
                        Icons.camera_alt,
                        color: Colors.white,
                        size: 30,
                      ),
                    ),
                  ),
                  Positioned(
                    left: 30,
                    right: 30,
                    top: 250,
                    child: Container(
                      height: 480,
                      child: SingleChildScrollView(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: <Widget>[
                            Padding(
                              padding: const EdgeInsets.only(top: 5),
                              child: SizedBox(
                                height: 70,
                                child: TextFormField(
                                  keyboardType: TextInputType.text,
                                  textCapitalization: TextCapitalization.sentences,
                                  textInputAction: TextInputAction.next,
                                  focusNode: Firstname,
                                  onFieldSubmitted: (value) {
                                    nextField(
                                        value: value, focusNode: LastndName);
                                  },
                                  controller: _textEditingControllerFirstNamee,
                                  decoration: InputDecoration(
                                    enabledBorder: OutlineInputBorder(
                                        borderRadius: BorderRadius.circular(
                                            5.0),
                                        borderSide: BorderSide(
                                            color: const Color(0x3df58634)
                                        )
                                    ),
                                    border: OutlineInputBorder(
                                        borderRadius: BorderRadius.circular(
                                            5.0)
                                    ),
                                    labelText: "First Name",
                                    labelStyle: GoogleFonts.nunito(
                                        color: const Color(0xfff58634)),
                                    hintText: "First Name",
                                    hintStyle: GoogleFonts.nunito(
                                        color: const Color(0xfff58634)),
                                    focusedBorder: OutlineInputBorder(
                                        borderRadius: BorderRadius.circular(
                                            5.0),
                                        borderSide: BorderSide(
                                          color: const Color(0x3df58634),
                                        )
                                    ),
                                  ),
                                  validator: (String value) {
                                    if (value.isEmpty) {
                                      return 'First Name is Required';
                                    }
                                    return null;
                                  },
                                  onSaved: (String value) {
                                    _Firstnm = value;
                                  },
                                ),
                              ),
                            ),
                            Padding(
                              padding: const EdgeInsets.only(top: 5),
                              child: SizedBox(
                                height: 70,
                                child: TextFormField(
                                  keyboardType: TextInputType.text,
                                  textCapitalization: 
     TextCapitalization.sentences,
                                  focusNode: LastndName,
                                  textInputAction: TextInputAction.next,
                                  onFieldSubmitted: (value) {
                                    nextField(value: value, focusNode: 
  Email);
                                  },
                                  controller: 
            _textEditingControllerLastnamee,
                                  decoration: InputDecoration(
                                    enabledBorder: OutlineInputBorder(
                                        borderRadius: BorderRadius.circular(
                                            5.0),
                                        borderSide: BorderSide(
                                            color: const Color(0x3df58634)
                                        )
                                    ),
                                    border: OutlineInputBorder(
                                        borderRadius: BorderRadius.circular(
                                            5.0)
                                    ),
                                    labelText: 'Last Name',
                                    labelStyle: GoogleFonts.nunito(
                                        color: const Color(0xfff58634)),
                                    hintText: "Last Name",
                                    hintStyle: GoogleFonts.nunito(
                                        color: const Color(0xfff58634)),
                                    focusedBorder: OutlineInputBorder(
                                        borderRadius: BorderRadius.circular(
                                            5.0),
                                        borderSide: BorderSide(
                                          color: const Color(0x3df58634),
                                        )
                                    ),
                                  ),
                                  validator: (String value) {
                                    if (value.isEmpty) {
                                      return 'First Name is Required';
                                    }
                                    return null;
                                  },
                                  onSaved: (String value) {
                                    _Lastnm = value;
                                  },
                                ),
                              ),
                            ),
                            Padding(
                              padding: const EdgeInsets.only(top: 5),
                              child: SizedBox(
                                height: 70,
                                child: TextFormField(
                                  focusNode: Email,
                                  textInputAction: TextInputAction.next,
                                  onFieldSubmitted: (value) {
                                    nextField(value: value, focusNode: DOB);
                                  },
                                  controller: _textEditingControllerEmaill,
                                  decoration: InputDecoration(
                                    enabledBorder: OutlineInputBorder(
                                        borderRadius: BorderRadius.circular(
                                            5.0),
                                        borderSide: BorderSide(
                                            color: const Color(0x3df58634)
                                        )
                                    ),
                                    border: OutlineInputBorder(
                                        borderRadius: BorderRadius.circular(
                                            5.0)
                                    ),
                                    labelText: 'Email',
                                    labelStyle: GoogleFonts.nunito(
                                        color: const Color(0xfff58634)),
                                    hintText: "Email",
                                    hintStyle: GoogleFonts.nunito(
                                        color: const Color(0xfff58634)),
                                    focusedBorder: OutlineInputBorder(
                                        borderRadius: BorderRadius.circular(
                                            5.0),
                                        borderSide: BorderSide(
                                          color: const Color(0x3df58634),
                                        )
                                    ),
                                  ),
                                  validator: (value) => EmailValidator.validate(value) ? null : "Please enter a valid email",
                                  onSaved: (String value) {
                                    _Email = value;
                                  },
                                ),
                              ),
                            ),
                          
                      
                            Padding(
                              padding: EdgeInsets.only(top: 45),
                              child: SizedBox(
                                width: 360,
                                height: 45,
                                child: RaisedButton(
                                  onPressed: () {
                                    if (!_formKey.currentState.validate()) {
                                      return;
                                    }
                                    setState(() {
                                      _isLoading = true;
                                    });
                                    Profile(
                                        _textEditingControllerFirstNamee.text,
                                        _textEditingControllerLastnamee.text,
                                        _textEditingControllerEmaill.text,
                                        _textEditingControllerDOBb.text,
                                        _textEditingControllerAnniversaryy
                                            .text,);
                                    Navigator.of(context).push(MaterialPageRoute(builder: (context) => ShelfScreen()));
                                  },
                                  shape: new RoundedRectangleBorder(
                                      borderRadius: new BorderRadius.circular(
                                          5.0)),
                                  color: const Color(0xfff58634),
                                  child: Text(
                                    "Update",
                                    style: GoogleFonts.nunito(
                                        color: const Color(0xffffffff),
                                        fontSize: 20
                                    ),
                                  ),
                                ),
                              ),

                            ),
                            Padding(
                              padding: EdgeInsets.only(top: 120),
                              child: Text(".", style: TextStyle(
                                color: Colors.transparent, fontSize: 1,
                              ),),

                            )
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            );
          } else {
            return CircularProgressIndicator();

    );
          }
        }
    )
 );
 }

 }
 class AlwaysDisabledFocusNode extends FocusNode {
 @override
 bool get hasFocus => false;
  }
api
flutter
sharedpreferences
asked on Stack Overflow Dec 4, 2020 by Raees Khatib • edited Dec 4, 2020 by Raees Khatib

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0