Ahmadre / FlutterIconPicker

An adaptive comprehensive IconPicker for Flutter
MIT License
112 stars 76 forks source link

Cant change icon after setting a default icon in code #8

Closed frederikw03 closed 4 years ago

frederikw03 commented 4 years ago

i have in my code saved what icon the user chooses earlier and set is as a default as seen here: 109729005_687493292098503_8436158623486473125_n

My code to auto fill the spot: ` Widget build(BuildContext context) {

icon = mapToIconData(new Map<String, dynamic>.from(widget.document['icon']));
_icon = Icon(icon);

` when i then try to choose a new icon it executes but its not chosen? it just keeps the icon i choose 'in code'

this is the code to open the picker ` _pickIcon() async {

icon = await FlutterIconPicker.showIconPicker(context, iconPackMode: IconPack.fontAwesomeIcons); _icon = Icon(icon); setState((){}); debugPrint('Picked Icon: $icon'); } `

Have i done something wrong? What can i do to fix this

Ahmadre commented 4 years ago

First: make sure your Map<String, IconData> is looking like this:

Bildschirmfoto 2020-07-26 um 00 13 13

Second: I need a reproducable code to help you as best as I can. Tip: use DartPad for example and share your pad here :)👍

frederikw03 commented 4 years ago
  1. my map does look like that.

  2. this is the code where i use it: import 'package:brew_crew/models/user.dart'; import 'package:brew_crew/services/database.dart'; import 'package:brew_crew/shared/constants.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:flutter_iconpicker/Models/IconPack.dart'; import 'package:provider/provider.dart';

import 'package:flutter_iconpicker/Serialization/iconDataSerialization.dart'; import 'package:flutter_iconpicker/flutter_iconpicker.dart';

class EditForm extends StatefulWidget { @override _EditFormState createState() => _EditFormState();

final Color mainColor; final DocumentSnapshot document;

EditForm({this.mainColor, this.document}); }

class _EditFormState extends State { final _formKey = GlobalKey();

// form values String _currentName; String _currentUrl; String iconError = ""; bool _clicked = false;

Widget _icon; IconData icon;

_pickIcon() async { icon = await FlutterIconPicker.showIconPicker(context, iconPackMode: IconPack.fontAwesomeIcons); _icon = Icon(icon); setState(() {}); debugPrint('Picked Icon: $icon'); }

@override Widget build(BuildContext context) { icon = mapToIconData(new Map<String, dynamic>.from(widget.document['icon'])); _icon = Icon(icon);

User user = Provider.of<User>(context);

return Form(
  key: _formKey,
  child: Column(
    children: <Widget>[
      Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[]),
      Text(
        'Edit the link',
        style: TextStyle(fontSize: 35.0),
      ),
      SizedBox(height: 20.0),
      AnimatedSwitcher(
          duration: Duration(milliseconds: 300),
          child: Container(
              height: 30, child: _icon != null ? _icon : Container())),
      RaisedButton(
        onPressed: _pickIcon,
        child: Text('Click to pick an Icon'),
        color: widget.mainColor,
      ),
      Text(
        iconError,
        style: TextStyle(color: Colors.redAccent[700], fontSize: 11),
        textAlign: TextAlign.left,
      ),
      SizedBox(height: 10),
      SizedBox(height: 20.0),
      TextFormField(
        keyboardType: TextInputType.url,
        decoration: InputDecoration(
          filled: true,
          prefixIcon: Icon(Icons.arrow_forward, color: widget.mainColor),
          labelText: "Name",
          fillColor: Colors.white,
          border: OutlineInputBorder(
            borderSide: BorderSide(color: widget.mainColor, width: 1.0),
            borderRadius: BorderRadius.circular(50.0),
          ),
        ),
        initialValue: widget.document['name'] ?? '',
        validator: (val) => val.isEmpty ? 'Please enter a name' : null,
        onChanged: (val) => setState(() => _currentName = val.trim()),
      ),
      SizedBox(height: 40.0),
      TextFormField(
        keyboardType: TextInputType.url,
        initialValue: widget.document['url'] ?? '',
        decoration: InputDecoration(
          filled: true,
          prefixIcon: Icon(Icons.link, color: widget.mainColor),
          labelText: "Link",
          fillColor: Colors.white,
          border: OutlineInputBorder(
            borderSide: BorderSide(color: widget.mainColor, width: 1.0),
            borderRadius: BorderRadius.circular(50.0),
          ),
        ),
        validator: (val) => val.isEmpty ? 'Please enter a valid url' : null,
        onChanged: (val) => setState(() => _currentUrl = val.trim()),
      ),
      SizedBox(height: 20.0),
      SizedBox(
        width: MediaQuery.of(context).size.width,
        height: 60,
        child: RaisedButton(
          color: widget.mainColor,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(50.0)),
          ),
          child: Text(
            'Save',
            style: TextStyle(color: Colors.white, fontSize: 25),
          ),
          onPressed: _clicked //prevents multiclickCrash
              ? null
              : () async {
                  _clicked = true;
                  if (_icon != null) {
                    setState(() {
                      iconError = "";
                    });
                  } else {
                    setState(() {
                      iconError = "Please pick an icon";
                    });
                  }
                  if (_formKey.currentState.validate() && _icon != null) {
                    await DatabaseService(uid: user.uid).updateSocialToData(
                        _currentName ?? widget.document['name'],
                        _currentUrl ?? widget.document['url'],
                        widget.document,
                        iconDataToMap(icon));
                    Navigator.pop(context);
                  }
                },
        ),
      ),
      SizedBox(height: 20.0),
      GestureDetector(
        onTap: () async {
          await Firestore.instance
              .runTransaction((Transaction myTransaction) async {
            await myTransaction.delete(widget.document.reference);
            await DatabaseService(uid: user.uid).deincriment();
          });
          Navigator.pop(context);
        },
        child: Text(
          "Delete",
          style: TextStyle(
            decoration: TextDecoration.underline,
            color: Colors.red,
            fontSize: 15,
          ),
        ),
      ),
      SizedBox(height: 20.0),
    ],
  ),
);

} }

frederikw03 commented 4 years ago

Can anyone help? :) would mean the world to me because I'm stuck

Ahmadre commented 4 years ago

At first: why are you doing this:

@override Widget build(BuildContext context) { icon = mapToIconData(new Map<String, dynamic>.from(widget.document['icon'])); _icon = Icon(icon);

Never initialize something in the build method when you want it to be done ONCE!

Implement the initial loading of your icon here in the initState: WidgetsBinding.instance.addPostFrameCallback((_) {...});

If you put everything in the build method it will build everytime you do setstate. This could lead to misleading behavior.

Second: I don't know your whole code. This code you gave us isn't a reproducable one. I don't know what you're doing in your Provider, or how this EditForm Widget is built in your widgets tree. But it has nothing to do with this package. Try the above suggestion or ask a question on StackOverflow, otherwise I hope it's just an override because of your implementation :)

frederikw03 commented 4 years ago

Thank you :) i fixed it by putting the code in the initState instead

Ahmadre commented 4 years ago

Glad to hear that :) I'll close this issue. Thank you for using my package 💙💙💙