settings_screen.dart 10.6 KB
Newer Older
Inomjon's avatar
Inomjon committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
import 'package:file_picker/file_picker.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'package:connectycube_sdk/connectycube_sdk.dart';

import '../src/constants/colors_const.dart';
import '../src/utils/app_utils.dart';
import 'managers/push_notifications_manager.dart';
import 'utils/api_utils.dart';
import 'utils/consts.dart';
import 'utils/pref_util.dart';
import 'widgets/common.dart';

class SettingsScreen extends StatelessWidget {
  final CubeUser currentUser;

  SettingsScreen(this.currentUser);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          leading: IconButton(
            icon:  Icon(Icons.close, color: ColorConst.appBleckColor),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
          automaticallyImplyLeading: false,
          title: const Text(
            'Settings',
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
          centerTitle: false,
        ),
        body: BodyLayout(currentUser),
        resizeToAvoidBottomInset: false);
  }
}

class BodyLayout extends StatefulWidget {
  final CubeUser currentUser;

  BodyLayout(this.currentUser);

  @override
  State<StatefulWidget> createState() {
    return _BodyLayoutState(currentUser);
  }
}

class _BodyLayoutState extends State<BodyLayout> {
  static const String TAG = "_BodyLayoutState";

  final CubeUser currentUser;
  var _isUsersContinues = false;
  String? _avatarUrl = "";
  final TextEditingController _loginFilter = new TextEditingController();
  final TextEditingController _nameFilter = new TextEditingController();
  final TextEditingController _emailFilter = new TextEditingController();
  String _login = "";
  String _name = "";
  String _email = "";

  _BodyLayoutState(this.currentUser) {
    _loginFilter.addListener(_loginListen);
    _nameFilter.addListener(_nameListen);
    _emailFilter.addListener(_emailListen);
    _nameFilter.text = currentUser.fullName ?? '';
    _loginFilter.text = currentUser.login ?? '';
    _emailFilter.text = currentUser.email ?? '';
  }

  void _loginListen() {
    if (_loginFilter.text.isEmpty) {
      _login = "";
    } else {
      _login = _loginFilter.text.trim();
    }
  }

  void _nameListen() {
    if (_nameFilter.text.isEmpty) {
      _name = "";
    } else {
      _name = _nameFilter.text.trim();
    }
  }

  void _emailListen() {
    if (_emailFilter.text.isEmpty) {
      _email = "";
    } else {
      _email = _emailFilter.text.trim();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        child: Center(
          child: ConstrainedBox(
            constraints: BoxConstraints(maxWidth: 400),
            child: Container(
              alignment: Alignment.center,
              padding: EdgeInsets.all(60),
              child: Column(
                children: [
                  _buildAvatarFields(),
                  _buildTextFields(),
                  _buildButtons(),
                  Container(
                    margin: const EdgeInsets.only(left: 8),
                    child: Visibility(
                      maintainSize: false,
                      maintainAnimation: false,
                      maintainState: false,
                      visible: _isUsersContinues,
                      child: AppUtils.buttonLoader
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildAvatarFields() {
    Widget avatarCircle = getUserAvatarWidget(currentUser, 50);

    return Stack(
      children: <Widget>[
        InkWell(
          splashColor: greyColor2,
          borderRadius: BorderRadius.circular(45),
          onTap: () => _chooseUserImage(),
          child: avatarCircle,
        ),
        Positioned(
          top: 55.0,
          right: 35.0,
          child: RawMaterialButton(
            onPressed: () {
              _chooseUserImage();
            },
            elevation: 2.0,
            fillColor: Colors.white,
            padding: const EdgeInsets.all(5.0),
            shape: const CircleBorder(),
            child: const Icon(
              Icons.mode_edit,
              size: 20.0,
            ),
          ),
        ),
      ],
    );
  }

  _chooseUserImage() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      type: FileType.image,
    );

    if (result == null) return;

    var uploadImageFuture = getUploadingImageFuture(result);

    uploadImageFuture.then((cubeFile) {
      _avatarUrl = cubeFile.getPublicUrl();
      setState(() {
        currentUser.avatar = _avatarUrl;
      });
    }).catchError((exception) {
      _processUpdateUserError(exception);
    });
  }

  Widget _buildTextFields() {
    return Column(
      children: <Widget>[
        TextField(
          controller: _nameFilter,
          decoration: const InputDecoration(labelText: 'Change name'),
        ),
        TextField(
          controller: _loginFilter,
          decoration: const InputDecoration(labelText: 'Change login'),
        ),
        TextField(
          controller: _emailFilter,
          decoration: const InputDecoration(labelText: 'Change e-mail'),
        ),
      ],
    );
  }

  Widget _buildButtons() {
    return Column(
      children: <Widget>[
        const SizedBox(
          height: 6,
        ),
        ElevatedButton(
          style: OutlinedButton.styleFrom(
            backgroundColor: ColorConst.appGreenColor,
            minimumSize: const Size(120, 36),
          ),
          onPressed: _updateUser,
          child: const Text('Save'),
        ),
        const SizedBox(
          height: 6,
        ),
        OutlinedButton.icon(
          style: OutlinedButton.styleFrom(
            backgroundColor: ColorConst.appMainColor,
            minimumSize: const Size(160, 36),
          ),
          icon: const Icon(
            Icons.logout,
          ),
          label: const Text('Logout'),
          onPressed: _logout,
        ),
        const SizedBox(
          height: 6,
        ),
        OutlinedButton.icon(
          style: OutlinedButton.styleFrom(
            foregroundColor: Colors.red.shade300,
            minimumSize: const Size(160, 36),
          ),
          icon: const Icon(
            Icons.delete,
            color: Colors.red,
          ),
          label: const Text(
            'Delete user',
            style: TextStyle(color: Colors.red),
          ),
          onPressed: _deleteUserPressed,
        ),
      ],
    );
  }

  void _updateUser() {
    print(
        '_updateUser user with login: $_login, name: $_name, e-mail: $_email');
    if (_login.isEmpty &&
        _name.isEmpty &&
        _avatarUrl!.isEmpty &&
        _email.isEmpty) {
      Fluttertoast.showToast(msg: 'Nothing to save');
      return;
    }
    var userToUpdate = CubeUser()..id = currentUser.id;

    if (_name.isNotEmpty) userToUpdate.fullName = _name;
    if (_login.isNotEmpty) userToUpdate.login = _login;
    if (_email.isNotEmpty) userToUpdate.email = _email;
    if (_avatarUrl!.isNotEmpty) userToUpdate.avatar = _avatarUrl;
    setState(() {
      _isUsersContinues = true;
    });
    updateUser(userToUpdate).then((user) {
      SharedPrefs.instance.updateUser(user);
      Fluttertoast.showToast(msg: 'Success');
      setState(() {
        _isUsersContinues = false;
      });
    }).catchError((exception) {
      _processUpdateUserError(exception);
    });
  }

  void _logout() {
    print('_logout $_login and $_name');
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text("Logout"),
          content: const Text("Are you sure you want logout current user"),
          actions: <Widget>[
            TextButton(
              child: const Text("CANCEL"),
              onPressed: () {
                Navigator.pop(context);
              },
            ),
            TextButton(
              child: const Text("OK"),
              onPressed: () {
                signOut().then(
                  (voidValue) {
                    Navigator.pop(context); // cancel current Dialog
                  },
                ).catchError(
                  (onError) {
                    Navigator.pop(context); // cancel current Dialog
                  },
                ).whenComplete(() {
                  CubeChatConnection.instance.destroy();
                  PushNotificationsManager.instance.unsubscribe();
                  FirebaseAuth.instance.currentUser
                      ?.unlink(PhoneAuthProvider.PROVIDER_ID);
                  SharedPrefs.instance.deleteUser();
                  Navigator.pop(context); // cancel current screen
                  _navigateToLoginScreen(context);
                });
              },
            ),
          ],
        );
      },
    );
  }

  void _deleteUserPressed() {
    print('_deleteUserPressed ${_login.isNotEmpty ? _login : _email}');
    _userDelete();
  }

  void _userDelete() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text("Delete user"),
          content: Text("Are you sure you want to delete current user?"),
          actions: <Widget>[
            TextButton(
              child: Text("CANCEL"),
              onPressed: () {
                Navigator.pop(context);
              },
            ),
            TextButton(
              child: Text("OK"),
              onPressed: () async {
                CubeChatConnection.instance.destroy();
                await SharedPrefs.instance.deleteUser();

                deleteUser(currentUser.id!).then(
                  (voidValue) {
                    Navigator.pop(context); // cancel current Dialog
                  },
                ).catchError(
                  (onError) {
                    Navigator.pop(context); // cancel current Dialog
                  },
                ).whenComplete(() async {
                  await PushNotificationsManager.instance.unsubscribe();
                  Navigator.pop(context); // cancel current screen
                  _navigateToLoginScreen(context);
                });
              },
            ),
          ],
        );
      },
    );
  }

  _navigateToLoginScreen(BuildContext context) {
    Navigator.pushNamedAndRemoveUntil(context, 'login', (route) => false);
  }

  void _processUpdateUserError(exception) {
    log("_processUpdateUserError error $exception", TAG);
    setState(() {
      _isUsersContinues = false;
    });
    showDialogError(exception, context);
  }
}